Linux Reading Data from UART

后端 未结 3 405
一个人的身影
一个人的身影 2021-01-21 16:45

I want to read data from UART, i followed this tutorial, the write function works as expected, however i\'am getting problem with the read function :

This is the uart_in

相关标签:
3条回答
  • 2021-01-21 17:18

    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 
    
    0 讨论(0)
  • 2021-01-21 17:20

    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.

    0 讨论(0)
  • 2021-01-21 17:28

    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;
    
    0 讨论(0)
提交回复
热议问题