【发布时间】:2020-10-17 06:38:57
【问题描述】:
我有串口转 USB 连接。 C打开/dev/ttyS0,python打开/dev/ttyUSB0。 C read(),来自 python 的 24 个字节。请参阅下面的 C 代码。
python 向 C 发送 24 个字节
ser.write(b'123456789012345678901234'.encode())
C 面没有打印。 如果我在字符串末尾添加 \n。
ser.write(b'123456789012345678901234\n'.encode())
然后在C端打印
get 24 bytes
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
get 24 bytes
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
get 1 bytes
似乎 read() 必须等待 '\n' 才能从函数 read() 返回。
我的问题是如何让 read() 在获取 24 个字节后返回?
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
int fd = 0;
int main()
{
int ret = 0;
fd = open( "/dev/ttyS0", O_RDWR );
if ( fd == -1 )
{
printf("open communication port fail");
ret = 1;
}
while(1)
{
uint8_t buf[100]={0};
int cnt = 0;
cnt = read(fd, buf, 24);
printf(" get %d bytes\n", cnt);
for ( int i = 0; i < cnt; i++ )
{
printf( "%c ", buf[i]);
}
printf("\n");
}
close(fd);
return 0;
}
【问题讨论】:
-
我认为这也适用于串行端口:stackoverflow.com/questions/54358053/… - 告诉我它是否适合您,我会投票将这个问题与那个问题联系起来
-
@user253751 这不会使终端脱离线路模式。终端需要输入raw mode。
-
您缺少设置终端波特率、模式和其他选项的代码。所以终端处于其默认模式,即线路模式。
-
谢谢大家的意见。似乎我需要将串口配置为原始模式。我会努力回来的。