【发布时间】:2019-02-11 08:28:13
【问题描述】:
我正在尝试从 STM32 Nucleo Board 获取数据(但这并不重要 ^^)。 我想获取原始数据并使用非规范模式,一切都准备好了。 我已将 VMIN 设置为 7 以等待 7 个字符未读并且读取也等待 7 个字符。 但是我的读取返回值之前得到 7 个值,我不明白为什么。 你有什么主意吗 ?我是否以错误的方式理解 VMIN ? 谢谢你帮助我!
我的代码:
int main(){
int r=-1;
char * device = "/dev/ttyS3";
pt = open(device, O_RDWR | O_NOCTTY | O_SYNC);
if(pt == -1){
perror("open");
exit(-1);
}
printf("open : %d\n",pt);
ioctl(pt, I_SRDOPT, RMSGD);
tcgetattr(pt, &old);
atexit(reset_tty);
tcgetattr(pt, &tty); // Get the current attributes of the Serial port
//cfmakeraw(&tty);
tty.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON | IXOFF);
tty.c_oflag &= ~(OPOST);
tty.c_cflag |= (CS8);
tty.c_cflag &= ~(CSIZE|PARENB);
tty.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
tty.c_cc[VMIN] = 7; // wait 7 characters
tty.c_cc[VTIME] = 0;
cfsetispeed(&tty,B9600); // Setting the Baud rate
cfsetospeed(&tty,B9600);
sleep(1);
r = tcflush(pt, TCIFLUSH);
printf("tcflush : %d\n",r);
r = tcsetattr(pt, TCSANOW, &tty);
printf("tcsetattr : %d\n",r);
int i = 0;
char end[20];
int count = 0;
char line[20];
memset(line,0,sizeof(line));
char forWrite[2]={'A','\0'};
while(count<10){
r = read(pt ,line,7);
printf("number of characters : %d\n",r);
printf("line = %s\n",line);
//printf("l = %c\n",line[0]);
count++;
memset(line,0,sizeof(line));
printf("\n");
}
return 0;
}
我的输出:
number of characters : 1
line =
number of characters : 2
line = 12
number of characters : 2
line = 33
number of characters : 5
line = 456ab
number of characters : 5
line = cdefg
number of characters : 1
line = a
number of characters : 4
line = bcde
number of characters : 2
line = fg
number of characters : 1
line = 1
number of characters : 3
line = 233
我从我的 STM32 发送“abcdefg”,然后是“1234567”
编辑:我发布的代码和输出是匹配的,我刚刚更改了我的打印,以便让你更清楚......我失败了^^,现在已经编辑了 thx :)
【问题讨论】:
-
你的 "code" (
printf("read : %d\n",r);and` printf("l = %s\n",line);) does not match your *"print"* output (number of characters : 1` and`线=`)。您发布的代码也不会在没有错误和警告的情况下编译。您需要提供minimal, complete, and verifiable example。 -
您的 termios 初始化有一个设置字符大小的错误。结果是您发布的代码将使用 5 位字符执行 I/O。 5 位不足以区分 ASCII 码中的数字和字母。因此,您发布的输出不可能由您发布的代码产生。
-
抱歉已编辑^^。一个错误?我可以修吗?你说 5 个字符是什么意思,而它似乎读取了随机数量的字符?
标签: c linux serial-port termios