linux: 串口接收十六进制部分字节丢失(0x11,0x0d->0x0a等等)

以下是一个简单的C++示例代码,用于在Linux上通过串口发送16进制数据并接收16进制返回值: ```cpp #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> int main(int argc, char *argv[]) { int fd; struct termios options; unsigned char buf[255]; // 打开串口设备 fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { perror("open_port: Unable to open /dev/ttyS0 - "); return -1; } // 配置串口 tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_cflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_iflag &= ~(IXON | IXOFF | IXANY); options.c_oflag &= ~OPOST; options.c_cc[VTIME] = 1; options.c_cc[VMIN] = 0; tcsetattr(fd, TCSANOW, &options); // 发送数据 unsigned char send_data[] = {0x01, 0x02, 0x03}; write(fd, send_data, sizeof(send_data)); // 接收返回值 int n = read(fd, buf, sizeof(buf)); if (n > 0) { printf("Received: "); for (int i = 0; i < n; i++) { printf("%02X ", buf[i]); } printf("\n"); } // 关闭串口设备 close(fd); return 0; } ``` 在此示例中,我们打开了/dev/ttyS0串口设备,并配置其波特率为9600。然后,我们发送了一个包含三个16进制字节数据包(0x01、0x02和0x03),并等待接收返回值。返回值存储在buf数组中,我们可以将其打印到控制台上。 请注意,此示例仅适用于简单的串口通信,并且可能需要进行更改以适应您的特定需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值