【问题标题】:Serial port communication in linux returns wrong answerslinux中的串口通信返回错误答案
【发布时间】:2014-02-26 10:27:06
【问题描述】:

我正在尝试创建一个 linux ubuntu 程序,该程序将从 tty 串行端口(Windows 中的 COM 端口)读取数据。我没有使用 USB 适配器,而是使用实际的 COM 端口。到目前为止,这是我的通信代码:

int OpenPort(void)
{
   int fd; // file description for sp

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

   if(fd == -1) // port not opened 
   {
      printf("Error:\n%s.\n", strerror(errno));
   }
   else
   {
      fcntl(fd, F_SETFL, 0);
      printf("Success.\n");
   }

   return(fd);
} // Open sp

void Communicate(void)
{
   struct termios settings;    

   tcgetattr( fd, &settings );

   cfsetispeed(&settings, B9600);    // Set bouds
   cfsetospeed(&settings, B9600);

   settings.c_cflag &= ~PARENB;    // set no parity, stop bits, data bits
   settings.c_cflag &= ~CSTOPB;
   settings.c_cflag &= ~CSIZE;
   settings.c_cflag |= CS8;

   tcflush( fd, TCIFLUSH );

   if (tcsetattr(fd, TCSAFLUSH, &settings)!= 0)
   {
      printf("Error message");
   }   

   //Create byte array
   unsigned char send_bytes[] = { 0x1, 0x6, 0x2, 0xAA, 0x2, 0x3, 0xB8, 0x4 };

   write(fd, send_bytes, sizeof(send_bytes));  // Send data
   printf("Data sent. \n");

   char buffer[64]; // buffer to receive data

   printf("I'm reading data...\n");
   int n = read(fd, buffer, sizeof(buffer));

   if (n < 0)
     printf("Failed to read\n");

   int i; 
   printf("Showing data...\n");

   for(i=0; i<sizeof(buffer); i++)
   {
      printf("Hex: %x\n", buffer[i]);
   } 

   printf("Closing...\n");

   close(fd);

   printf("All done!\n");
}

我这里有几个问题:

  1. 在我运行程序后,一旦它正确执行,但当我尝试再次运行它时,它会在“我正在读取数据...”处停止,并且即使在我重新启动计算机后也不会启动。一段时间后,它允许我再次执行程序。
  2. 程序返回数据后,它应该向我发送十六进制数据,例如 A7、9F 等,但这会给我整数值。
  3. 我应该以及如何清除缓冲区数组以释放内存

谁能帮助解决这些问题?

【问题讨论】:

    标签: c linux serial-port tty


    【解决方案1】:

    'int n = read(fd, buffer, sizeof(buffer));'返回在 n 中读取的字节数,然后您将忽略它(除了检查负错误值之外),并假设缓冲区已完全填满。这是一个错误,因为 recv() 通常不会等待请求的字节数,因为串行端口提供的是字节流,而不是“缓冲区”或“消息”。

    printf("十六进制: %x\n", buffer[i]);将显示整数,因为您使用 %x 指定整数。仔细查看 printf 格式代码。

    【讨论】:

    • 我不确定我是否理解正确。我的代码没有通过这个没有完全填充的缓冲区数组,它只是停在这里,所以我不能对 n 做任何事情。另外,我不知道端口将提供多少字节,只是它不会超过 64,所以有什么方法可以检查我收到的字节数。在 c# 程序中我做了这样的事情: array[] buf = new array[port.BytesToRead]; port.read(buf);
    • 我试图用读写和程序工作(当然不正确)注释掉行,所以它似乎没有读取或写入任何数据到串行端口并返回。我的设置有什么问题???
    猜你喜欢
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2014-12-04
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    相关资源
    最近更新 更多