I've got an app that reads characters from a serial port, evaluates these characters and then responds if necessary. I have it working somewhat, but it's not totally reliable. The main issue is that I have a while loop that constantly reads input but I can't figure out how to determine when new characters are sent -- it just reads constantly, sets a variable and outputs it. So, if the master device sends two characters, "0x61, 0x20", My output looks like this:

61
20
20
20
20
20
...and so on forever, since the var that holds the input hasn't been reset.

The bigger issue is that depending on the timing of the while loop, old characters may get mixed up with new input from the master device, which throws everything off. I need the loop to STOP outputting until it knows for sure that new characters are being sent.

Example:

Code:
int fd_serialport;
struct termios options;

fd_serialport = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

if(fd_serialport == -1){
	perror("Unable to open /dev/ttyS0");
}

tcgetattr(fd_serialport, &options);
cfsetispeed(&options, B38400);
cfsetospeed(&options, B38400);
options.c_cflag |= (CLOCAL | CREAD);	
options.c_cflag |= PARENB;
options.c_cflag |= PARODD;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_iflag |= (INPCK | ISTRIP);
tcsetattr(fd_serialport, TCSANOW, &options);
	
fcntl(fd_serialport, F_SETFL, FNDELAY);

while(read(fd_serialport, &data_in[0], sizeof(char))){
		
	printf("%s\n",&data_in[0]);
	usleep(2000);
}