[英]Receive extra null byte when using serial port
我正在為Linux上的串行端口數據傳輸編寫程序,但是發現發送方每次打開端口時,接收方都會得到一個額外的空字節'\\x00'
。
這是發件人的代碼:
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
int main(int argc, char* argv[]) {
int fd_com_ = open("/dev/ttyAM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
struct termios attrs_;
attrs_.c_iflag = IGNBRK;
attrs_.c_oflag = 0;
attrs_.c_cflag = (CLOCAL | CREAD);
attrs_.c_cflag |= CS8;
attrs_.c_lflag = 0;
attrs_.c_cc[VMIN] = 0;
attrs_.c_cc[VTIME] = 0;
cfsetspeed(&attrs_, B115200);
tcsetattr(fd_com_, TCSANOW, &attrs_);
const char *s = "abcd";
write(fd_com_, s, 4);
sleep(1);
write(fd_com_, s, 4);
sleep(1);
close(fd_com_);
fd_com_ = open("/dev/ttyAM0", O_RDWR | O_NOCTTY | O_NONBLOCK);
write(fd_com_, s, 4);
return 0;
}
接收者具有相同的配置,但是接收到"\\x00abcdabcd\\x00abcd"
。 如何解決此問題,以便接收者可以獲取"abcdabcdabcd"
?
更新:
接收方代碼:
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
int main(int argc, char* argv[]) {
int fd_com_ = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
struct termios attrs_;
attrs_.c_iflag = IGNBRK;
attrs_.c_oflag = 0;
attrs_.c_cflag = (CLOCAL | CREAD);
attrs_.c_cflag |= CS8;
attrs_.c_lflag = 0;
attrs_.c_cc[VMIN] = 0;
attrs_.c_cc[VTIME] = 0;
cfsetspeed(&attrs_, B115200);
tcsetattr(fd_com_, TCSANOW, &attrs_);
char buf[100];
ssize_t sz;
while(1) {
sz = read(fd_com_, buf, 100);
if (sz > 0) {
for (ssize_t i=0; i<sz; i++) {
printf("%02hhx\n", buf[i]);
}
}
sleep(1);
}
return 0;
}
請檢查ARM板的文檔,以了解如何連接ARM的UART,以及如何在硬件中以及通過平台驅動程序對其進行配置。
根據您的描述,我假設在打開ARM上的UART端口時,已啟用物理UART(即ARM內的硬件外圍模塊或也許是外部連接的UART芯片)或從某些未知的空閑狀態恢復到了UART。 RS232的正確-12伏空閑狀態。 此晶體管轉移可能足以使您的PC的UART識別起始位並接收虛假字符。
您可能需要使用示波器檢查串行線,以查看實際打開端口時發生的情況。
初始\\x0
表示發生奇偶校驗或成幀錯誤。 發生此錯誤是因為termios字段未正確設置。 因此初始行的高/低狀態以及開始/停止位數和奇偶校驗設置不正確。
您可能會閱讀: http : //man7.org/linux/man-pages/man3/termios.3.html ,其中討論了每個字段及其內容和含義。
(鏈接的頁面太長了,無法在此處發布)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.