Linux Reading Data from UART

会有一股神秘感。 提交于 2019-12-01 23:36:55

Your program is hanging in the read() syscall because it is blocked waiting for a line-termination character.
You tried to configure the port for non-canonical mode with the statement

SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Non Cannonical mode  

but that operation is on the wrong termios element.
The ICANON attribute is part of the lflag element (and not the iflag). (This error originates from the tutorial you referenced!)
Therefore your program is performing blocking canonical reads.

There's a convenient termios function for configuring non-canonical mode:

   cfmakeraw()  sets the terminal to something like the "raw" mode of the old 
   Version 7 terminal driver: input is available character by
   character, echoing is disabled, and all special processing of  
   terminal  input  and  output  characters  is  disabled.   The  terminal
   attributes are set as follows:

       termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                       | INLCR | IGNCR | ICRNL | IXON);
       termios_p->c_oflag &= ~OPOST;
       termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
       termios_p->c_cflag &= ~(CSIZE | PARENB);
       termios_p->c_cflag |= CS8;

There's an error in the read function

bytes_read = read(fd,&read_buffer,10); /* Read the data 

should be

bytes_read = read(fd,read_buffer,10); /* Read the data 
ryyker

Your read() function may be blocked, for whatever reason. Here is a discussion on reading from a serial port, including code for blocked/unblocked settings.

It may also be possible that there is no data being transferred, leading to nothing being read. Without having access to the hardware setup, it is difficult to go further without very specific information about what you are seeing.

Also, in addition to passing the read_buffer correctly (another answer), there are at least two additional things that may improve:

1) check the return of read before using it:

bytes_read = read(fd,&read_buffer,10); /* Read the data*/
if(bytes_read > 0)
{
    ...
}

2) Change:

for(i=0;i<bytes_read;i++)   /*printing only the received characters*/
 printf("%c",read_buffer[i]);

To:

//after successful read:
read_buffer[bytes_read]=0;//place null termination after last character read.
printf("%s",read_buffer);//note format specifier

This will print the number of characters read, without the loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!