[英]Read data from a serial port to USB in Ubuntu using C++
I have a GPS that has a serial port, and it has a transfer cable from serial to USB. 我有一个具有串行端口的GPS,并且具有从串行到USB的传输电缆。 It is connected to the laptop through USB, and is transmitting data in Hex.
它通过USB连接到笔记本电脑,并以十六进制传输数据。 I want to use this data in my C++ code on Ubuntu.
我想在Ubuntu上的C ++代码中使用此数据。 Any ideas where could I start, and how I could manage to read the data?
有什么想法可以从哪里开始,以及如何设法读取数据?
Start by opening a file (fstream, FILE * or OS handle) to "/dev/ttySn" where n
is the number of the device, then read away. 首先将文件(fstream,FILE *或OS句柄)打开到“ / dev / ttySn”,其中
n
是设备编号,然后将其读出。
#include <string>
#include <fstream>
#include <iostream>
std::string str;
std::fstream f;
f.open("/dev/ttyS0");
while (f >> str)
{
std::cout << str;
}
That should "echo" out the contents of ttyS0 - that may of course be the "wrong" port for your device, but if you know where it is connected that should do the job. 这应该“回显” ttyS0的内容-当然,这可能是设备的“错误”端口,但是如果您知道它的连接位置,那应该可以完成工作。 You may also need to set the configuration of the port.
您可能还需要设置端口的配置。 For example, using the
stty
command - baudrate would be the most important, so something like stty -F /dev/ttyS0 19200
will set the baudrate (actually bitrate) to 19200 bits per second. 例如,使用
stty
命令-波特率将是最重要的,因此,类似stty -F /dev/ttyS0 19200
会将波特率(实际上是比特率)设置为每秒19200位。 Most other parameters are probably ok. 大多数其他参数可能还可以。
#include <iostream>
#include <fstream>
int main () {
std::string str;
std::fstream f;
f.open("/dev/ttyS0");
while (f >> str)
{
std::cout << str;
}
}
Here's a working snippet. 这是一个工作片段。 When I had this question I struggled to find the needed
include
statements and the correct namespace. 当我遇到这个问题时,我很难找到所需的
include
语句和正确的名称空间。
This answer was based on Mats Petersson's answer 该答案基于Mats Petersson的答案
Edit: This would be more appropriate as a comment to Mats Petersson's answer. 编辑:这将更适合作为Mats Petersson答案的评论。 The comment could be:
评论可能是:
"
#include fstream
forfstream
and#include iostream
forstring
andcout
. The namespace offstream
andcout
isstd
."“
#include fstream
为fstream
和#include iostream
的string
和cout
。的命名空间fstream
和cout
是std
。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.