Hello guys, i have a code which used to connect my hardware through the USB port. Sending data in HEX format and when the hardware reply or gives out an output, it will direct go to a .txt file.
PROBLEM: Sometimes the output data from the hardware is correct and sometimes not. seems like i'm missing something like flushing/cleaning something before any process is done. please do point which line and how to solve it. Thanks in advanced. Below is the code:
Code:
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <stdlib.h>
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0) { /* Could not open the port */
fprintf(stderr, "open_port: Unable to open /dev/ttyUSB0 - %s\n",
strerror(errno));
}
return (fd);
}
void main()
{
int mainfd=0, i; /* File descriptor */
char cnt, result2;
unsigned char result,chout;
struct termios options;
FILE *fp;
mainfd = open_port();
fcntl(mainfd, F_SETFL, FNDELAY); /* Configure port reading */
/* Get the current options for the port */
tcgetattr(mainfd, &options);
cfsetispeed(&options, B19200); /* Set the baud rates to 19200 */
cfsetospeed(&options, B19200);
/* Enable the receiver and set local mode */
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB; /* Mask the character size to 8 bits, no parity */
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8; /* Select 8 data bits */
options.c_cflag &= ~CRTSCTS; /* Disable hardware flow control */
/* Enable data to be processed as raw input */
options.c_lflag &= ~(ICANON | ECHO | ISIG);
/* Set the new options for the port */
tcsetattr(mainfd, TCSANOW, &options);
tcflush(mainfd, TCIOFLUSH); // Clear both the input and output buffers.
result2 = tcsetattr(mainfd, TCSANOW, &options);
if ( result2 == -1 ) { perror("error: tcsetattr"); }
if ( result2 != 0 ) { fprintf(stderr,"error in tcsetattr, result = %d\n", result2); }
result2 = write(mainfd,"\xF5\x23\x00\x00\x00\x00\x23\xF5",8);
if ( result2 == -1 ) { perror("error: write"); }
if ( result2 != 8 ) { fprintf(stderr,"error in write, result = %d\n", result2); }
usleep(3000000); /* wait for 3 second*/
fp = fopen("results_eigenvalue.txt", "w"); /*open and write into existing file*/
for(i=0;i<207;i++)
{
result = read(mainfd, &chout, sizeof(chout)); /* Read character from ABU (Auto buffering Unit) */
if ( result == -1 ) { perror("error: read"); }
if ( i >= 12){
fprintf(fp,"%d ",chout); }
}
close(mainfd); /* Close the serial port */
}