I've read all the related questions here but didn't find the solution.
I'm trying to read one by one byte from the serial port.
- When I'm in infinite loop and I check if some bytes are available, it always works fine and displays what ever I send to it.
- But when I check outside of the infinite loop it just catch one byte, display it, then close the serial port.
Here is my code
// Checks if 1 data byte is available in the RX buffer at the moment
int serialHasChar(int fd)
{
struct pollfd fds;
fds.fd = fd;
fds.events = (POLLIN | POLLPRI); // POLLIN : There is data to read, POLLPRI: There is urgent data to read
if(poll(&fds, 1, 0) > 0)
{
return 1;
}
else
{
return 0;
}
}
int serialOpen(const char *port, const uint baud)
{
int fd = -1;
fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
printf("[ERROR] Couldn't open port \"%s\": %s\n", port, strerror(errno));
return -1;
}
else
{
printf("Serial port %s successfully opened\n", port);
}
struct termios options;
tcgetattr(fd, &options); // Get the current attributes of the Serial port
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
options.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);
return fd;
}
void serialClose(int fd)
{
tcflush(fd, TCIOFLUSH);
close(fd);
printf("Serial port successfully closed\n");
}
// Receive one byte
uint8_t serialReadChar(int fd)
{
uint8_t ch;
//tcflow(fd, TCOON);
read(fd, &ch, 1);
//tcflow(fd, TCOOFF);
printf("One byte received : 0x%.2x\n", ch);
return ch;
}
int main()
{
uint8_t bytes = 0;
uint8_t ch = 0;
// Open serial port
int fd = serialOpen("/dev/ttyAMA0", 115200);
// This works
while(1)
{
if (serialHasChar(fd)) {
ch = serialReadChar(fd);
}
}
/* This doesn't work
while(serialHasChar(fd) == 0);
while(serialHasChar(fd))
{
ch = serialReadChar(fd);
bytes++;
//bytes = serialNumOfAvailableBytes(fd);
}
*/
serialClose(fd);
return 0;
}
I don't understand why does it happen so!! Could someone help me? Thanks
UPDATE: I've added the definition of serialHasChar() function in the code above