我写了一个C++应用程序,需要从串口读取数据(由集成的Arduino Leonardo发送),解释并保存。我在串行端口上收到两条后续消息:一条来自GPS设备(通过串行传递),另一条来自一些传感器的数据
我已经可以读取数据了,但是我在解释数据时遇到了困难。来自GPS的数据采用SBP协议进行二进制打包Protocol structure.
我可以使用Python struct轻松读取和保存它,如下所示:
if ser.read().hex() == "55":
if ser.read(2).hex() == "0102":
ser.read(7) # unnecessary information
lat = struct.unpack('d', ser.read(8))[0]
lon = struct.unpack('d', ser.read(8))[0]
alt = struct.unpack('d', ser.read(8))[0]
ser.read(4) # unnecessary information
n_sats = struct.unpack('B', ser.read(1))[0]
flag = (struct.unpack('B', ser.read(1))[0]) % 4
<>但是我在C++中正努力实现这个(我需要它在C++中实现)。我正在把数据读入这样的缓冲区#include "Serial.h"
#include "SerialReader.h"
#include <iostream>
#ifdef _WIN32
const char *port = "COM3";
#else
const char *port = "/dev/ttyUSB0";
#endif
using namespace std;
const uint16_t sizeBuf = 512;
int main()
{
CSerial serial; //Serial object
uint8_t *buf = new uint8_t[sizeBuf];
//Tries to open connection to COM port
while (tryCont < 10) {
if (serial.Open(port, 38400)) {
cout << "Port opened successfully" << endl;
break;
}
else {
cout << "Failed to open port! Trying again..." << endl;
tryCont++;
Sleep(5000);
}
if (tryCont >= 10) {
cout << "Impossible to open port" << endl;
return 0;
}
}
while (true) {
serial.ReadData(buf, sizeBuf); //Reads data from serial and stores in buffer
}
}
在阅读本文时,我希望数组的每个位置都有一个字节,并像在Python代码中那样对它们进行比较和处理,但事实并非如此。消息的第一个字节是十六进制0x55,但我的缓冲区中有buf(0)=0x05和buf(1)=0x05。 我尝试了很多方法,但都没能让它更具可读性。除了这个问题,我还需要从多个字节的值中读取信息,这方面我也有问题。我真的是个笨蛋,如果有什么明显的事情,我很抱歉
下面是打印缓冲区时读取数据的示例(我在数组的每个成员之间放置了一个空格,以显示我所说的内容)。我希望是55,然后是01等等,而不是5,5,0,1
5 5 0 1 E D 9 B F B 6 4 0 6 A A F 0 0 0 0 5 5 6 A 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 1 5 5 D 7 5 5 5 5 5 5 B D 5 5 5 5 5 5 0 5 5 F F 5 5 E D 5 5 0 5 5 E 5 5 5 1 8 5 5 7 0 5 5 0 5 5 F D 5 5 5 5 5 5 5 5 5 5 0 9 0 3 C 4 E 5 5 5 2 E D 9 1 6 8 5 9 B 2 0 2 4 F 3 F F F F A 1 F 6 F F F F 0 0 0 0 0 0 0 0 9 0 8 8 6 C 5 5 4 2 E D 9 1 4 8 5 9 B 2 0 E D F 3 F F F F 6 7 F E F F F F C 3 F 5 F F F F 0 0 9 0 1 8 6 D 5 5 2 2 E D 9 1 4 8 5 9 B 2 0 E 2 3 E F F F F F 3 1 D 1 0 1 B B 7 0 0 0 0 9 1 2 C 7 F 5 5 3 2 E D 9 1 6 8 5 9 B 2 0 3 E 6 0 0 4 6 C 4 F E F F 0 0 0 0 0 0 0 0 9 1 F 1 2 5 5 1 2 E D 9 2 2 8 5 9 B 2 0 7 D 1 6 3 B 7 6 1 9 B 7 4 2 4 0 2 8 A E C 7 3 E 2 3 8 B 5 E C 0 9 D 2 0 C F 8 6 4 1 8 C 5 1 4 0 0 0 0 0 9 1 C F C 9 5 5 0 2 E D 9 2 0 8 5 9 B 2 0 3 B 6 A 1 A 4 5 2 0 9 A 4 4 C 1 7 8 D 8 6 8 4 C C C 5 F 5 0 C 1 B 6 8 6 9 1 9 B 3 C 6 A 4 D 4 1 0 0 9 1 A E 8 A
我用这个library来做串行连接部分
目前没有回答
相关问题 更多 >
编程相关推荐