python - 如何立即从串行端口读取字节而不是等待换行符?
问题描述
我有串行到 USB 连接。C打开/dev/ttyS0,python打开/dev/ttyUSB0。C read(),来自 python 的 24 个字节。请参阅下面的 C 代码。
python将24个字节发送到C
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;
}
解决方案
除了注释中的建议外,通常在循环中放置变量退出条件会很有用:
例如, from :while(some_variable < some_value)
while(1)
至
int cnt = 0;//declare and initialize before loop
while(cnt < 24 )
break;
一旦满足退出条件,您也可以在循环中添加一条语句。例如类似于:
...
cnt = read(fd, buf, 24);
if(cnt == 24)
{
printf(" get %d bytes\n", cnt);
for ( int i = 0; i < cnt; i++ )
{
printf( "%c ", buf[i]);
}
printf("\n");
break;
}
....
推荐阅读
- r - R中的正则表达式和ID
- node.js - AWS lambda 在节点 js 中获取处理程序或上下文信息
- powershell - Powershell 创建新的注册表值
- python - Sympy:如何显示导致被零除的条件?
- python - 如何从 Python 中的内存中 mp4 文件(字节缓冲区)中提取帧?
- sql - 寻找删除违规记录的 SQL 连接示例(行删除行清理 SQL 连接)
- php - 无法将多维数组转换为单个 php 数组
- angular - 路由到与当前页面相关的另一个组件页面时如何保持 routerLinkActive 设置?
- python - 在 MESA 中删除代理
- html -