C 中 Raspberry PI 串行通信中的奇偶校验设置问题

Problem with Parity setting in Serial Communication on Raspberry PI in C

我从 Raspberry PI 发送字节,并使用终端程序通过串行通信端口在笔记本电脑上接收它们。通信参数如下:

波特率:9600,数据位:8,奇偶校验:ODD,停止位:1,握手:None.

发送两个字节后 {0x10, 0x05} 我在终端(在我的笔记本电脑中)收到 {0x10, 0xC1}。仅当我将终端上的奇偶校验更改为 NONE.

时,我才能接收到正确的字节

如何将奇偶校验设置为 ODD

请参阅下面的代码:

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

int main()
{

    struct termios RSopt;
    char str[3] = { 0x10, 0x05, 0x0};
    int fd;
    fd = open( "/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY );    

    tcgetattr( fd, &RSopt);
    cfmakeraw( &RSopt);
    cfsetspeed ( &RSopt, (speed_t)B9600);
    RSopt.c_cflag &= ~CSIZE;  
    RSopt.c_cflag |= CS8;     
    RSopt.c_cflag |= PARENB;  
    RSopt.c_cflag |= PARODD; 
    RSopt.c_cflag &= ~CSTOPB; 
    tcflush( fd, TCIFLUSH );
    tcsetattr ( fd, TCSANOW, &RSopt); 

    write( fd, str, 2 );
    close( fd );

}
Raspberry PI 系统上的

ttyS0 是 mini-uart,不支持奇偶校验位。参见:https://www.raspberrypi.org/documentation/configuration/uart.md

您发布的代码在其他方面基本上是正确的。我目前没有可访问的 RPi,但如果驱动程序正确实现,您应该还可以通过检查 tcsetattr() 的 return 值来验证属性的正确应用,并验证通过检查 tcgetattr() 设置的值来更改,因为 setattr 可能仅在 NONE 个属性可以设置时才指示失败。