繁体   English   中英

Linux从UART读取数据

[英]Linux Reading Data from UART

我想从UART读取数据,我按照本教程操作 ,写功能按预期工作,但是读功能出现问题:

这是uart_init函数:

void uart_init()
{
 printf("\n +----------------------------------+");
 printf("\n |        Serial Port Write         |");
 printf("\n +----------------------------------+");

/*------------------------------- Opening the Serial Port -------------------------------*/

  fd = open("/dev/ttyUSB0",O_RDWR | O_NOCTTY| O_SYNC);      /* !!blocks the read  */
                                                            /* O_RDWR Read/Write access to serial port           */
                                                            /* O_NOCTTY - No terminal will control the process   */
                                                            /* O_NDELAY -Non Blocking Mode,Does not care about-  */
                                                            /* -the status of DCD line,Open() returns immediatly */                                        

 if(fd == -1)                                               /* Error Checking */
  printf("\n  Error! in Opening ttyUSB0  ");
 else
  printf("\n  ttyUSB0 Opened Successfully ");


 /*---------- Setting the Attributes of the serial port using termios structure --------- */

struct termios SerialPortSettings;          /* Create the structure                          */

tcgetattr(fd, &SerialPortSettings);         /* Get the current attributes of the Serial port */

cfsetispeed(&SerialPortSettings,B19200);        /* Set Read  Speed as 19200                       */
cfsetospeed(&SerialPortSettings,B19200);        /* Set Write Speed as 19200                       */

SerialPortSettings.c_cflag &= ~PARENB;          /* Disables the Parity   Enable bit(PARENB),So No Parity   */
SerialPortSettings.c_cflag &= ~CSTOPB;          /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
SerialPortSettings.c_cflag &= ~CSIZE;           /* Clears the mask for setting the data size             */
SerialPortSettings.c_cflag |=  CS8;             /* Set the data bits = 8                                 */

SerialPortSettings.c_cflag &= ~CRTSCTS;         /* No Hardware flow Control                         */
SerialPortSettings.c_cflag |= CREAD | CLOCAL;   /* Enable receiver,Ignore Modem Control lines       */ 


SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);          /* Disable XON/XOFF flow control both i/p and o/p */
SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Non Cannonical mode                            */

SerialPortSettings.c_oflag &= ~OPOST;/*No Output Processing*/

/* Setting Time outs */
SerialPortSettings.c_cc[VMIN] = 10; /* Read at least 10 characters */
SerialPortSettings.c_cc[VTIME] = 0; /* Wait indefinetly   */

if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) /* Set the attributes to the termios structure*/
 printf("\n  ERROR ! in Setting attributes");
else
 printf("\n  BaudRate = 19200 \n  StopBits = 1 \n  Parity   = none");

}

接收功能:

void uart_receive()
{
 char read_buffer[32];   /* Buffer to store the data received              */
 int  bytes_read = 0;    /* Number of bytes read by the read() system call */
 int i = 0;

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

 printf("\n\n  Bytes Rxed %d", bytes_read); /* Print the number of bytes read */
 printf("\n\n  ");

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

 printf("\n +----------------------------------+\n\n\n");
}

主要功能:

void main(void)
{ 
  uart_init();
  /*------------------------------- Write data to serial port -----------------------------*/
  //uart_write_commande(write_buffer); //Write function works well
  uart_receive();

  close(fd);/* Close the Serial port */
}

编辑

我执行程序并等待在UART中接收数据字节,我使用UART发送数据,但读取功能一直处于阻塞状态。

我正在使用带有Ubunutu 14.04的虚拟机,但不确定使用仿真的UART会在接收期间引起问题。

读取功能有错误

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

应该

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

您的程序挂在read()系统调用中,因为它被阻止等待行终止符。
您尝试使用以下语句将端口配置为非规范模式

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

但是该操作是在错误的termios元素上进行的。
所述ICANON属性是lflag元件(而不是IFLAG)的一部分。 (此错误源自您引用的教程!)
因此,您的程序正在执行阻止规范读取。

有一个方便的termios函数可用于配置非规范模式:

   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;

无论出于何种原因,您的read()函数都可能被阻止。 这是关于从串行端口读取的讨论 ,包括阻止/取消阻止设置的代码。

也有可能没有数据在传输,导致什么也没有被读取。 如果无法访问硬件设置,那么如果没有关于所看到内容的非常具体的信息,则很难走得更远。

此外,除了正确传递read_buffer(另一个答案)外,至少还有两个其他方面可以改进:

1)在使用前检查read的返回:

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

2)变更:

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

至:

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

这将打印读取的字符数,而不循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM