Linux串行端口:输入中缺少数据
Linux Serial Port: missing data on input
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <cerrno>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef struct termios ComSet;
int main()
{
int acm=-1;
acm=open("/dev/ttyACM0",O_RDWR | O_NOCTTY);
if(acm == -1)
{
cout<<"Error Opening ttyACM0"<<endl;
exit(1);
}
else
{
cout<<"Preparing ttyACM0..."<<endl;
ComSet SerialSettings;
tcgetattr(acm, &SerialSettings);
cfsetispeed(&SerialSettings,B9600);
cfsetospeed(&SerialSettings,B9600);
/* 8N1 Mode */
SerialSettings.c_cflag &= ~PARENB;
SerialSettings.c_cflag &= ~CSTOPB;
SerialSettings.c_cflag &= ~CSIZE;
SerialSettings.c_cflag |= CS8;
SerialSettings.c_cflag &= ~CRTSCTS;
SerialSettings.c_cflag |= CREAD | CLOCAL;
SerialSettings.c_iflag &= ~(IXON | IXOFF | IXANY);
SerialSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);
SerialSettings.c_oflag &= ~OPOST;
/* Setting Time outs */
SerialSettings.c_cc[VMIN] = 10; /* Read at least 10 characters */
SerialSettings.c_cc[VTIME] = 0; /* Wait indefinetly */
if((tcsetattr(acm,TCSANOW,&SerialSettings)) != 0)
{
cout<< " ERROR ! in Setting attributes"<<endl;
}
else
{
cout<< "=======ttyACM0 Setting====="<<endl;
cout<<"BaudRate = 9600 StopBits = 1 Parity = none"<<endl;
cout<<"Reading ttyACM0... "<<endl;
char read_buffer[1024];
bzero(read_buffer,1024);
int read_bytes=0;
while(1)
{
tcflush(acm, TCIFLUSH);
read_bytes=read(acm,&read_buffer,1024);
if(read_bytes>0)
{
cout<<read_buffer;
bzero(read_buffer,1024);
}
}
}
close(acm); /* Close the serial port */
}
return 0;
}
出于某种原因,代码无法正常工作我正试图从arduino中读取,因为它早些时候工作正常,它给了我抓取的输出如
世界啊!你好,世界!ello世界!llo世界!llo世界!
改变的是
在终端输出中有一条额外的新行,这是使用cat/dev/ttyAMC0
你好,世界!
你好,世界!
你好,世界!
你好,世界!
你好,世界!
我想逐行读取,因为它是由arduino发送到终端的
当您得到像lo World ! Hello World ! ello World !
这样的乱码输出时,通常表明您的时钟速度(波特率(不匹配。请确保您的Arduino的写入速度为9600波特。
此外,当Arduino输出字符时,它会将它们放在硬件缓冲区中。read()
函数从缓冲区中取出指定的字节数,在本例中为1024。但您可能不希望每次读取1024个字节。相反,我认为你应该读到换行符。查看您正在使用的库中是否有readline()
函数。
Linux cat
命令读取正确,但该命令本身在末尾添加了一个额外的换行符。
相关文章:
- c ++数据输入并读回列表中的结构结构中的数组
- 为什么我不能从结构将数据输入到字符数组中?
- C 如何忽略错误数据输入
- 如何在 C++ 中将结构类型向量数据输入到结构向量成员(嵌套结构向量)中
- 使用 for 循环多次将数据输入到 txt 文件
- C 从文本文件中将数据输入INT矢量
- 将数据输入两个字符串
- 带有 QSqlTableModel 的 QTableView 的数据输入
- C++用户将数据输入 2D 数组的最简单方法是什么?
- C++LinkedList数据输入
- 将数据输入到 2-D 数组中,这是如何工作的
- C++ 将数据输入私有向量时遇到问题(使用无效)
- 使数据输入字段记住其值,从一次运行到下一次运行
- C++ 将数据输入到用户定义类型的向量
- 我不知道如何正确地将数据输入到地图中
- 如何通过输入终止数据输入
- WHILE循环和数据输入
- 不按我的要求显示数据输入表单
- 用键盘将数据输入Qt GUI:按下回车键时会产生意想不到的副作用
- c++为不符合条件的数据输入创建循环