Input within a time limit in Standard C - c

I'm currently doing my assignment and it's compulsory to use C-Free 5.0. Just need your help to solve this piece of puzzle. I want to implement a time limit for the user to input an answer before it expires. I've tried this code but it got block at scanf() function. Is there any other method like an unblocking input or something. I've tried to implement '#include <sys/select.h>' but this program doesn't have that library.
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
int main()
{
char st[10];
printf ("Please enter a line of text : ");
time_t end = time(0) + 5; //5 seconds time limit.
while(time(0) < end)
{
scanf("%s", &st);
if(st != NULL)
{
printf ("Thank you, you entered >%s<\n", st);
exit(0);
}
}
main();
}

Here is an example program that shows how you can use O_NONBLOCK flag on a stdin file descriptor.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define INPUT_LEN 10
int main()
{
printf ("Please enter a line of text : ");
fflush(stdout);
time_t end = time(0) + 5; //5 seconds time limit.
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
char answer[INPUT_LEN];
int pos = 0;
while(time(0) < end)
{
int c = getchar();
/* 10 is new line */
if (c != EOF && c != 10 && pos < INPUT_LEN - 1)
answer[pos++] = c;
/* if new line entered we are ready */
if (c == 10)
break;
}
answer[pos] = '\0';
if(pos > 0)
printf("%s\n", answer);
else
puts("\nSorry, I got tired waiting for your input. Good bye!");
}

Since you have fcntl.h try setting stdin to non-blocking. It's not pretty (active waiting), but if you do not have select then this is the easyest way to go:
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
// get stdin flags
int flags = fcntl(0, F_GETFL, 0);
if (flags == -1) {
// fcntl unsupported
perror("fcntl");
return -1;
}
// set stdin to non-blocking
flags |= O_NONBLOCK;
if(fcntl(0, F_SETFL, flags) == -1) {
// fcntl unsupported
perror("fcntl");
return -1;
}
char st[1024] = {0}; // initialize the first character in the buffer, this is generally good practice
printf ("Please enter a line of text : ");
time_t end = time(0) + 5; //5 seconds time limit.
// while
while(time(0) < end // not timed out
&& scanf("%s", st) < 1 // not read a word
&& errno == EAGAIN); // no error, but would block
if (st[0]) // if the buffer contains something
printf ("Thank you, you entered >%s<\n", st);
return 0;
}
A remark to your code: if (st != NULL) will always be satisfied since st is a stack pointer.

Related

How to make synchronism between two distinct C programs?

First of all, I don't know if I can explain well my problem or you can get it in the appropriate way. But I will try to make it clear for you.
In fact, I have two different C programs.
The first one is a simple loop print of a message on the console :
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main ()
{
while(1)
{
printf("WAITING\n");
sleep(1);
}
}
The second one is a blocking program that waits for an event ( press button ) to turn on led in my embedded board.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
#include <linux/input.h>
#define BTN_FILE_PATH "/dev/input/event0"
#define LED_PATH "/sys/class/leds"
#define green "green"
void change_led_state(char *led_path, int led_value)
{
char lpath[64];
FILE *led_fd;
strncpy(lpath, led_path, sizeof(lpath) - 1);
lpath[sizeof(lpath) - 1] = '\0';
led_fd = fopen(lpath, "w");
if (led_fd == NULL) {
fprintf(stderr, "simplekey: unable to access led\n");
return;
}
fprintf(led_fd, "%d\n", led_value);
fclose(led_fd);
}
void reset_leds(void)
{
change_led_state(LED_PATH "/" green "/brightness", 0);
}
int configure_leds(void)
{
FILE *l_fd;
FILE *r_fd;
char *none_str = "none";
/* Configure leds for hand control */
r_fd = fopen(LED_PATH "/" green "/trigger", "w");
fprintf(r_fd, "%s\n", none_str);
fclose(r_fd);
/* Switch off leds */
reset_leds();
return 0;
}
void eval_keycode(int code)
{
static int green_state = 0;
switch (code) {
case 260:
printf("BTN left pressed\n");
/* figure out red state */
green_state = green_state ? 0 : 1;
change_led_state(LED_PATH "/" green "/brightness", green_state);
break;
}
}
int main(void)
{
int file;
/* how many bytes were read */
size_t rb;
int ret;
int yalv;
/* the events (up to 64 at once) */
struct input_event ev[64];
char *str = BTN_FILE_PATH;
printf("Starting simplekey app\n");
ret = configure_leds();
if (ret < 0)
exit(1);
printf("File Path: %s\n", str);
if((file = open(str, O_RDONLY)) < 0) {
perror("simplekey: File can not open");
exit(1);
}
for (;;) {
/* Blocking read */
rb= read(file, &ev, sizeof(ev));
if (rb < (int) sizeof(struct input_event)) {
perror("simplekey: short read");
exit(1);
}
for (yalv = 0;
yalv < (int) (rb / sizeof(struct input_event));
yalv++) {
if (ev[yalv].type == EV_KEY) {
printf("%ld.%06ld ",
ev[yalv].time.tv_sec,
ev[yalv].time.tv_usec);
printf("type %d code %d value %d\n",
ev[yalv].type,
ev[yalv].code, ev[yalv].value);
/* Change state on button pressed */
if (ev[yalv].value == 0)
eval_keycode(ev[yalv].code);
}
}
}
close(file);
reset_leds();
exit(0);
}
When I execute the second code, the program starts waiting for the event to switch on/off the led.
My question is :
How can I make interaction between the two programs ? I want to execute the firs one --> It starts printing for me " WAITING " until I press the BUTTON --> the LED turn on --> and then it goes back to the first program and re-start printing " WAITING " on the console.
I don't know if I explained well the issue but I hope that you can help me! Thank you.
You need a communication mechanism between your two programs. This is also known als inter-process communication.
Generally, you have several options to achieve this (depending on the operating system you are using, not all of them may be available):
Shared memory / shared files
Message passing (e.g. via sockets)
Pipes
Signals
A helpful introduction can be found here.

Can't redirect stdin to another process and have that process answer back correctly

I have a project to do in C where I have to make a game where 2 clients talk with a server, and that server handles the plays, and then responds to each of them, one at the time, until the game is finished.
I'm doing this for weeks now and I managed to do something like:
Server has a fork somewhere where the child, exec() a game (supplied by me) and I redirect that output to the client (very crudely I might add ...), and an unnamed pipe for speaking with his parent.
The client receives that output, sees the game board and sends a play to the server.
The parent uses the other end of the unnamed pipe to receive what the client sent and sends it to the child.
As soon as the first play is done, the server enters in a loop of "invalid plays" but I don't send anything. What is going on? Can anyone point me in the right direction?
Restrictions of this project are that we can only use pipes and fifos (not threads or sockets) and open, close, read and write. Only printfs allowed on the game.c code.
Example of a run:
Open server with ./server, open client with ./client John. In client, type 1 and enter. Then type 1 1 and enter to make a play. Then, the error occurs.
client.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <signal.h>
void main(int argc, char *argv[])
{
int fdfifo_CS, fdfifo_SC, fd, conta;
char buffer[400];
int num=0;
fdfifo_CS = open("fifo_publico_cliente_servidor", O_WRONLY);
fdfifo_SC = open("fifo_privado_servidor_cliente", O_RDONLY);
write(fdfifo_CS, argv[1], strlen(argv[1])+1);
while(1)
{
num = read(fdfifo_SC,buffer,sizeof(buffer));
write(1,buffer,num);
num = read(0,buffer,sizeof(buffer));
write(fdfifo_CS, buffer, num);
num = read(0,buffer,sizeof(buffer));
write(fdfifo_CS, buffer, num);
}
server.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <signal.h>
#include <dirent.h>
void main(int argc, char *argv[])
{
int fdfifo_CS, fdfifo_SC, num=0, pid=0, fd, pipefd[2];
char buffer[1024];
write(1, "\nServer ON !\n", strlen("\nServer ON !\n"));
mkfifo("fifo_publico_cliente_servidor",0777);
fdfifo_CS = open("fifo_publico_cliente_servidor", O_RDWR);
mkfifo("fifo_privado_servidor_cliente",0777);
fdfifo_SC = open("fifo_privado_servidor_cliente", O_WRONLY);
num = read(fdfifo_CS,&buffer,sizeof(buffer));
do
{
write(fdfifo_SC,"\n\n!!! Menu !!!\n", strlen("\n\n!!! Menu !!!\n"));
write(fdfifo_SC,"----------------------------------------------\n", strlen("----------------------------------------------\n"));
write(fdfifo_SC,"1) Play.\n", strlen("1) Play.\n"));
write(fdfifo_SC,"Choose: ", strlen("Choose: "));
read(fdfifo_CS,buffer,sizeof(buffer));
switch(buffer[0])
{
case '1':
pipe(pipefd);
pid = fork();
if (pid == 0)
{
fd = open("/dev/pts/8", O_RDWR, 0777); //To redirect to the bash of the client used. Must be changed to the correct tty.
dup2(fd,1);
close(fd);
close(pipefd[1]);
dup2(pipefd[0],0);
close(pipefd[0]);
execl("game","game",(char*) NULL);
}
else
{
close(pipefd[0]);
num = read(fdfifo_CS, buffer, sizeof(buffer));
write(pipefd[1], buffer, num);
close(pipefd[1]);
}
break;
default:
printf("DONE");
break;
}
}while(1);
}
game.c
#include <unistd.h>
#include <stdio.h>
#include <string.h>
void print_table(char *p, char t[3][3]) {
printf("\nO:%s: %c|%c|%c\n", p, '1', '2', '3');
printf("O:%s:1 %c|%c|%c\n", p, t[0][0], t[0][1], t[0][2]);
printf("O:%s: -+-+-\n", p);
printf("O:%s:2 %c|%c|%c\n", p, t[1][0], t[1][1], t[1][2]);
printf("O:%s: -+-+-\n", p);
printf("O:%s:3 %c|%c|%c\n\n", p, t[2][0], t[2][1], t[2][2]);
}
/* check if this was a winning play */
int winning_play(int x, int y, char t[3][3]) {
int v = t[y-1][x-1];
if (t[y-1][0] == v && t[y-1][1] == v && t[y-1][2] == v)
return 1;
if (t[0][x-1] == v && t[1][x-1] == v && t[2][x-1] == v)
return 1;
if ((x + y % 2 == 0 && /* part of a diagonal */
t[0][0] == v && t[1][1] == v && t[2][2] == v) ||
(t[0][2] == v && t[1][1] == v && t[2][0] == v))
return 1;
return 0;
}
int main() {
char table[3][3] =
{ {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };
char play[16];
int stop = 0, win = 0, turn = 1, turns = 0;
do {
int x, y, check;
/* display table to both players */
print_table("12", table);
turn = (turn + 1) % 2;
turns++;
do {
/* display message to the current player */
printf("OUT:%d: play (format \"x y\")?\n", turn+1);
/* ask for input from current player */
printf("IN:%d\n", turn+1);
fgets(play, sizeof(play), stdin);
check = (sscanf(play, "%d%d", &x, &y) == 2 &&
x >= 1 && x <=3 && y >= 1 && y <= 3 &&
table[y-1][x-1] == ' ');
if (check == 0)
/* display message to current player */
printf("OUT:%d: invalid play\n", turn+1);
} while (!check);
table[y-1][x-1] = (turn == 0 ? 'X' : 'O');
win = winning_play(x, y, table);
stop = (turns == 9);
} while (!stop && !win);
/* display final table to both players */
print_table("12", table);
/* display final score to both players */
if (win)
printf("RES:12: winner %d\n", turn+1);
else
printf("RES:12: draw\n");
return 0;
}

Converting chars to int from serial port in C

I am using this source code to read from the serial port of a linux machine. I am able to read from the port, but all of the values are in ascii gibberish ( i am reading the input from an xbox controller). I know I am sending it correctly, i.e. i can see on my side I am sending -128 - 127 as a char, but when I am converting it on my linux machine using atoi its returning 0, or when I try to cast the data to int it returns -48 , equivalent to 0 in ascii.
Is there a way for me to convert the incoming ascii into a readable integer like 64 or -114? I appreciate any help, thank you.
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include "rs232.h"
int main()
{
int i, n,
cport_nr=0, /* /dev/ttyS0 (COM1 on windows) */
bdrate=9600; /* 9600 baud */
unsigned char buf[4096];
char mode[]={'8','N','1',0};
if(RS232_OpenComport(cport_nr, bdrate, mode))
{
printf("Can not open comport\n");
return(0);
}
while(1)
{
n = RS232_PollComport(cport_nr, buf, 4095);
if(n > 0)
{
buf[n] = 0; /* always put a "null" at the end of a string! */
for(i=0; i < n; i++)
{
if(buf[i] < 32) /* replace unreadable control-codes by dots */
{
buf[i] = '.';
}
}
printf("received %i bytes: %s\n", n, (char *)buf);
}
#ifdef _WIN32
Sleep(100);
#else
usleep(100000); /* sleep for 100 milliSeconds */
#endif
}
return(0);
}

client/server print out array and write back

I am using C and putty to write a client/server program.
Both c files are on the same system.
I am currently having an issue with writing back to the client the frames it is using as well as printing out my frames. It prints out 3 0 9 8 but then it starts printing out 13456756 etc.
Here is what I have:
server:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
main (void)
{
int to_server; // to read from client
int from_server; // to write to client
int finish; // lets me know that client is done
int i,j,k,m,l; // because C needs this defined as int
int numClient;// number of clients
char temp[14];
int page_size = 128;
int pages_left;
int max_frames=10;
int used_frames =0;
int frameUpdate=0;
int freeframe[10] = {3,0,9,8,7,5,1,4,2,6}; //this is the array
int numpage=0;
int frames;
int check;
int option;
int byte;
int getPage;
int getOffset;
int physical_Addr;
int offset;
int req[3];
int again;
struct values{
char privFifo[14];
int memoryreq;
}cinput;
/* Create the fifos and open them */
if ((mkfifo("FIFO1",0666)<0 && errno != EEXIST))
{
perror("cant create FIFO1");
exit(-1);
}
if((to_server=open("FIFO1", O_RDONLY))<0){
printf("cant open fifo to write");
}
//get number of clients
printf("\nHow many clients?\n");
scanf("%d", &numClient);
for(j =1; j <= numClient; j++){
read(to_server, &cinput, sizeof(cinput));
printf("\n\nFifo_%d \nMemory request %d", &cinput.privFifo, cinput.memoryreq);
req[j-1] = cinput.memoryreq;
if((mkfifo(cinput.privFifo,0666)<0 && errno != EEXIST))
{
perror("cant create privFifo");
exit(-1);
}
if((from_server=open(cinput.privFifo, O_WRONLY)<0)){
printf("cant open fifo to write");
}
// find number of pages need for request
numpage = cinput.memoryreq/page_size;
if((numpage * page_size) < cinput.memoryreq){
numpage++;
}
sleep(1);
printf("\nPages needed %d", numpage);
write(from_server, &numpage, sizeof(numpage));
printf("\n******Main Memory******");
for(m = used_frames; m < numpage; m++){
printf("\n* client: %d\tframe: %d", j, freeframe[m]);
frames = freeframe[m];
write(from_server, &frames, sizeof(frames));
}
used_frames = max_frames - used_frames;
pages_left = max_frames - numpage;
//this is where I try to print out the available frames
printf("\n Frames available:");
for(l = pages_left; l!= 0; l--){
check = max_frames - l;
printf(" %d", freeframe[check]);
max_frames = check;
}
close(from_server);
unlink(cinput.privFifo);
}
printf("\nDONE!!!");
close(to_server);
unlink("FIFO1");
client:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
main (void)
{
int to_server; // to write to server
int from_server;
char temp[14]; // server puts string here
int clientID;
//int frames;
int numpage;
int i;
struct values{
char privFifo[14];
int memoryreq;
}cinput;
if((to_server=open("FIFO1", O_WRONLY))<0)
printf("cant open fifo to write\n");
printf("writing data to to_server\n");
printf("Client: Please enter number of memory units: ");
scanf("%d", &cinput.memoryreq);
printf("%d", cinput.memoryreq);
clientID = getpid();
sprintf(cinput.privFifo, "Fifo_%d", getpid());
printf("\nFifo name is %s", &cinput.privFifo);
write(to_server, &cinput, sizeof(cinput));//write client pid and memUnit to server
sleep(2); //give time to send
printf("\nClient: Got the character sent, now waiting for response ");
if ((mkfifo(cinput.privFifo,0666)<0 && errno != EEXIST))
{
perror("cant create FIFO1");
exit(-1);
}
if((from_server=open(cinput.privFifo, O_RDONLY))<0){
printf("cant open fifo to write");
}
read(from_server, &numpage, sizeof(numpage));
printf("\nFrames Occupied %d", numpage);
close(to_server);
close (from_server);
unlink(cinput.privFifo);
printf ("\nall done!\n");
}
Any help is greatly appreciated. Thank you.
I strongly suspect the problem is the line used_frames = max_frames - used_frames;. Since used_frames is initially 0, that sets it one past the end of the array for the second iteration, so you start printing values past the end of your frame array when you run for(m = used_frames; m < numpage; m++). (By the way: please indent properly.). But set a breakpoint and run in a debugger to be sure.

UART compare charts. Beaglebone

I have a problem trying to compare the uart input data (from a GPS) with '$' in order to detect a new package. I am sure that the problem is in how I manipulate the charRead variable. I tried one thousand of things, but probably because of my inexperience I have not figured out what it is the problem.
The code compiles and the data is coming all the time, but once I load the code into the beaglebone, it gets stacked but and it doesn't enter in the "if (charRead =='$')".
Thank you in advance!
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
#include <iostream>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include "Payload.h"
#define SLOTS "/sys/devices/bone_capemgr.9/slots"
#define CR 0x0d
#define SPACE 0x20
#define COMMA 0x2C
#define MAXSIZE 100
unsigned long time_data;
unsigned int button = 45;
int i,z =0, j=0, value;
int rx_length;
int main()
{
//uart4 configuration using termios
int fd;
//unsigned char *mess;
unsigned int value = 0;
gpio_export(button);
//Wait until the button is pushed
while (value != 1){
if (z==0){
printf("waiting\n");}
z++;
gpio_get_value(button, &value);}
//OPEN THE UART
//open uart4 for tx/rx, not controlling device
if((fd = open("/dev/ttyO4", O_RDONLY | O_NOCTTY|O_NONBLOCK)) < 0){
printf("Unable to open uart4 access.\n");
}
termios uart4;
cfsetospeed(&uart4, B9600); //Set the speed
//set attributes of uart4
uart4.c_iflag = 0;
uart4.c_oflag = 0;
uart4.c_lflag = 0;
tcsetattr(fd, TCSANOW, &uart4);
//----- CHECK FOR ANY RX BYTES -----
// Read up to 100 characters from the port if they are there
unsigned char stringRead[MAXSIZE];
unsigned char charRead;
do{
if (rx_length = read(fd, (void*)charRead, MAXSIZE)>0){
if (charRead =='$'){
i=0;
stringRead[i] = charRead; //Store in the first position of the char --> $
do {
rx_length = read(fd, (void*)charRead, MAXSIZE); //Read the next bit
if( (charRead != '\0') ) {
i++;
stringRead[i] = charRead; //write into stringRead
}
} while(charRead != 'CR'); //ASCII Carriage Return
stringRead[i+1] = charRead;
printf("%s", stringRead);
}}
if (rx_length==0){
//No data
}
gpio_get_value(button, &value);
}while (value!=0);
gpio_unexport(button);
close(fd);
return 0;
}
You're passing a cast of the variable value of charRead rather than a pointer to a memory location as the function read() expects void *.
read(fd, (void*)charRead, MAXSIZE)
You need to either read one character at a time:
read(fd, &charRead, 1)
Or change your reading logic to maximize amount read and data processing. I also recommend adding a bounds check on accessing stringRead.
// The following should handle the reading of a GPS NMEA message and display it
// I have not run the program, but compiling it was successful
// note:
// 1) the handling of the 'i' variable
// 2) the calls to reading the GPS input
// 3) the handling of error conditions
// 4) the simple logic flow
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
//#include <iostream> // this is not C++ so this line not needed
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include "Payload.h"
// #define SLOTS "/sys/devices/bone_capemgr.9/slots" // not used, raises compiler warning
#define CR (0x0D)
// #define SPACE (0x20) // not used, raises compiler warning
// #define COMMA (0x2C) // not used, raises compiler warning
#define MAXSIZE (100)
#define BUTTON_PORT (45)
// unsigned long time_data; // not used, raises compiler warning
// int j=0; // not used, raises compiler warning
// int value = 0; // not used, raises compiler warning about variable masking
int main()
{
int i;
int z = 0; // flag used to control execution flow
int rx_length; // return status value from read()
//uart4 configuration using termios
int fd; // file descriptor number
//unsigned char *mess; // not used, raises compiler warning
unsigned int value = 0;
gpio_export(BUTTON_PORT);
//Wait until the button is pushed
// burn mass CPU cycles, while waiting
while (0 == value)
{
if (z==0)
{
printf("waiting\n");
z++; // to stop re-entry to this 'if' block
}
// suggest using nsleep() to free up CPU
gpio_get_value(BUTTON_PORT, &value);
} // end while
//open uart4 for rx
if((fd = open("/dev/ttyO4", O_RDONLY | O_NOCTTY|O_NONBLOCK)) < 0)
{
perror("open failed for /dev/tty04");
exit(1);
}
// implied else, open successful
termios uart4;
cfsetospeed(&uart4, B9600); //Set the speed to match the GPS output
//set attributes of uart4
// Note: probably better to read the current termois values
// then modify them to the desired states
uart4.c_iflag = 0;
uart4.c_oflag = 0;
uart4.c_lflag = 0;
tcsetattr(fd, TCSANOW, &uart4);
//----- CHECK FOR ANY RX BYTES -----
// Read up to 100 characters from the port if they are there
unsigned char stringRead[MAXSIZE]; // will contain a GPS NMEA message
unsigned char charRead; // input buffer
do{
while(1)
{
rx_length = read(fd, &charRead, 1);
if( 0 == rx_length )
{ // this will execute a lot since fd set to non-blocking
; // do nothing, while hogging CPU cycles
// suggest using nsleep() to free CPU
}
else if( 0 > rx_length )
{
perror( "read failed" );
exit(1);
}
else if (charRead =='$')
{
stringRead[0] = charRead; //Store first char of NMEA GPS message
i=1; // index for second char of NMEA message from GPS
}
else
{
stringRead[i] = charRead; //Store char
i++; // index for next char into stringRead buffer
if( MAXSIZE <= i )
{ // then overrun input buffer
perror( "read- overrun input buffer, GPS message too long");
exit(2);
}
if( CR == charRead ) //ASCII Carriage Return - end of message
{ // then, got complete message
break; // exit read loop, so can process message
}
} // end if
} // end while
stringRead[i] = '\0'; // terminate string so it can be printed
printf("%s", stringRead);
// get button state via BUTTON_PORT(45)
gpio_get_value(BUTTON_PORT, &value);
} while (value!=0); // then read next gps message
gpio_unexport(BUTTON_PORT);
close(fd);
return 0;
}

Resources