【发布时间】:2021-08-23 14:28:32
【问题描述】:
我有一个 gps 模块,它每 1 秒向串口发送一次数据(NMEA 语句)。我一直在尝试从 C++ 程序中读取它。
用picocom读取串口时,数据以干净的方式显示,每一行都有一个NMEA语句)。
我的程序的结果很接近,但有时会混淆。
这是我的代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
int main(){
struct termios tty;
memset(&tty, 0, sizeof tty);
int serial_port = open("/dev/ttyUSB0", O_RDWR);
// Check for errors
if (serial_port < 0) {
printf("Error %i from open: %s\n", errno, strerror(errno));
}
// Read in existing settings, and handle any error
if(tcgetattr(serial_port, &tty) != 0) {
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
}
tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common)
tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common)
tty.c_cflag |= CS8; // 8 bits per byte (most common)
tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)
tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO; // Disable echo
tty.c_lflag &= ~ECHOE; // Disable erasure
tty.c_lflag &= ~ECHONL; // Disable new-line echo
tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes
tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
tty.c_cc[VTIME] = 10;
tty.c_cc[VMIN] = 0;
// Set in/out baud rate to be 9600
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
// Save tty settings, also checking for error
if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
}
// Allocate memory for read buffer, set size according to your needs
char read_buf [24];
memset(&read_buf, '\0', sizeof(read_buf));
while(1){
int n = read(serial_port, &read_buf, sizeof(read_buf));
std::cout << read_buf ;
}
return 0;
}
picocom 如何正确显示数据?是由于我的缓冲区大小还是 VTIME 和 VMIN 标志?
【问题讨论】:
-
看起来该程序的源代码位于GitHub | picocom。
picocom.c看起来很有趣。 -
谢谢!我会看看的。
标签: c++ linux serial-port nmea