[英]Redundancy when reading USB serial port (C;Mac OSX;Arduino)
我正在寫一個簡單的C程序,它可以從連接到我的Arduino設備的USB端口讀取數據。 Arduino以4字節的塊為單位以波特率9600輸出數據。
我想從Arduino到我的電腦的輸入看起來像這樣:
136.134.132.130.129.127.126.124.121.119.117.115.113.111。
但是,我得到這樣的東西:
271.274.281..2.4062.4022.40225.4021
問題:如何在C程序中獲取輸入以與丟失數據/重讀數據整齊地同步? 當端口有新數據時,是否有某種標志可以告訴我的程序?
碼:
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/types.h>
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/tty.usbmodemfd121", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/tty");
}
else
fcntl(fd, F_SETFL, 0);
struct termios options;
tcgetattr(fd,&options);
cfsetospeed(&options,B9600);
options.c_cflag |=(CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
return (fd);
}
int main (){
int i;
for(i=0; i<50; i++){
fcntl(open_port(), F_SETFL, FNDELAY);
char buf[5];
size_t nbytes;
ssize_t bytes_read;
nbytes = sizeof(buf);
bytes_read = read(open_port(), buf, nbytes);
printf("%s ", buf);
buf[0]=0;
}
return 0;
}
您的程序未正確打開()串行端口以進行讀取。
實際上,它在for循環的每次迭代中重復打開兩次。
該程序只能打開一次該設備。
代替
for (i=0; i<50; i++) {
fcntl(open_port(), F_SETFL, FNDELAY);
bytes_read = read(open_port(), buf, nbytes);
}
主程序的結構應該像
fd = open_port();
if (fd < 0) {
/* handle error condition */
}
rc = fcntl(fd, F_SETFL, FNDELAY);
if (rc < 0) {
/* handle error condition */
}
for (i=0; i<50; i++) {
bytes_read = read(fd, buf, nbytes);
if (bytes_read < 0) {
/* handle error condition */
}
}
close(fd);
你的程序太“簡單”了。 它只設置了幾個屬性,並且無需檢查系統調用的返回碼。
這應該是規范的還是非規范的(又稱原始的)模式(即數據ASCII文本還是二進制)?
有關正確設置串行端口的信息,請參閱本串行編程指南 。
從USB端口讀取數據
USB是一種總線。
程序讀取的設備是連接到該USBus的串行端口。
第二個編碼問題
您的原始代碼可能會打印垃圾數據。
nbytes = sizeof(buf);
bytes_read = read(open_port(), buf, nbytes);
printf("%s ", buf);
buf[0]=0;
read()操作返回的字節不太可能被NULL字節終止,因此該讀取緩沖區上的字符串操作可能超出分配的數組的邊界。
不會行為不端的代碼會是這樣的:
nbytes = sizeof(buf) - 1;
bytes_read = read(fd, buf, nbytes);
if (bytes_read < 0) {
/* handle error condition */
} else {
buf[bytes_read] = 0; /* append terminator */
printf("%s ", buf);
}
請注意, nbytes比緩沖區的分配大小小1。
這是為了確保當read()操作返回nbytes的“完整”緩沖區時,有一個可用字節來存儲字符串終止符字節。
為了提高效率,應在進入for循環之前執行nbytes的賦值,而不是在循環內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.