UART read not working..

TRINATH KARRI

New Member
Credits
35
Hi,
I am unable to read UART data from COM port ttyS0. Read is being blocked (since it is a blocking call) and it gets triggered and data is read from UART once i run cutecom application. Please let me know if any changes are required for my code given below.

Code :


#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>

int main()
{
int fd, n;
char buf[100]= {0};
struct termios options;

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

if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyS0 ");
}
else
{
fcntl(fd, F_SETFL, O_RDWR | O_NOCTTY);
}


if(tcgetattr(fd, &options) != 0)
{
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
return 1;
}

options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag |= CRTSCTS;
options.c_cflag |= (CREAD | CLOCAL);

options.c_lflag &= ~ICANON;
options.c_lflag &= ~ECHO;
options.c_lflag &= ~ECHOE;
options.c_lflag &= ~ECHONL;
options.c_lflag &= ~ISIG;

options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);

options.c_oflag &= ~OPOST;
options.c_oflag &= ~ONLCR;

options.c_cc[VTIME] = 100;
options.c_cc[VMIN] = 0;

cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);

if (tcsetattr(fd, TCSANOW, &options) != 0)
{
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
return 1;
}

while(1)
{
printf("Waiting to read\n");

n = read(fd, buf, 100);

if(n != 0)
buf[n]='\0';

if (n <= 0)
fputs("read() failed!\n", stderr);
else
printf("read bytes = %d, read val = %s\n", n, buf);

sleep(1);
}
}



Thanks in advance...
 


wizardfromoz

Super Moderator
Staff member
Gold Supporter
Credits
14,465
I haven't answered your conversation to me, questions are answered in Forum.

Hello. Try to exercise a little patience.

Please don't ask support questions in conversations, they won't get answered.

Questions in Forum are answered, if someone has knowledge on the matter, and they are awake at the time. Your country is not the centre of the world, and there are timezones.

Click the button near top that says Forums and take a look around.

If this is a networking question, then it should be placed there. Placing it in Getting Started, it will just disappear off the front page in 24 hours, with other questions.

Once you establish where your question should be, let us know and I will move it there.

Also take a read of this article

https://linuxtips.gq/2021/01/19/how-to-ask-a-good-support-question/

Thank you

Chris Turner
wizardfromoz
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!


Top