C++ 输出与 Python 不同的消息(从串口读取)
C++ outputs different message than Python (Reading from serial port)
总结
我有两个程序;一个用 Python3 编写,另一个用 C++ 编写。两者执行相同的任务;从串行端口读取,过滤掉两个 header 浮点数,并打印剩余的消息。 Python 脚本正常工作(请参阅下面的输出以获取正确的数字); C++ 的,使用 serial 库,没有,我不明白为什么。 (运行 Raspberry Pi 4,Raspbian 克星)。
为了避免有人阅读整篇文章;如果我决定使用这个库进行串行读取是错误的,我怎样才能正确地从 C++ 中的串行端口读取?
我试过的
我是 C++ 的新手,所以也许我找错了地方,但我找不到一个普遍接受的用于从串口读取的库,所以我选择了最有用的库github (serial) 上的星星。
This 答案给出了 windows 的示例和指向几个库的链接,但是它们要么是为了与 windows 一起使用,要么是在 C 中,而不是在 C++ 中。
使用另一个库。
This 在 C 中(我的代码将与 Simulink-based C++ class 一起编译,所以我认为我需要坚持使用 C++ (?))
我的代码
Python
这是功能齐全的 Python 代码:
import serial
import struct
import time
PORT_NUMBER = '/dev/ttyACM0'
BAUDRATE = 115200
MESSAGE_LENGTH = 8
HEADER_NUMBER = float(112)
header_1_received = False # Has the first header byte been received
header_2_received = False # Has the second header byte been received
dat = [] # The actual message
# Open serial port
ser = serial.Serial(
port=PORT_NUMBER,
baudrate=BAUDRATE,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=0.001)
ser.isOpen()
readings = 0
print('Receive data from Pixhawk using 2 header floats and {} message floats (32-bit) \nIf you wish to close the program, hit \"Ctrl+C\" on your keyboard and it (should) shut down gracefully.'.format(MESSAGE_LENGTH))
start_time = time.time() # Start time for the program
try:
# Main loop
while (True):
# Read 4 bytes (32-bits) to get a full float number
buffer = ser.read(4)
# Only proceed if the buffer is not empty (an empty buffer is b'')
if buffer != b'':
# Since struct.unpack() returns a tuple, we only grab the first element
try:
new_dat = struct.unpack("f",buffer)[0]
if header_1_received==True and header_2_received==True:
dat.append(new_dat)
elif new_dat == HEADER_NUMBER:
# We found a header single; treat it
if header_1_received == False:
header_1_received = True
elif header_2_received == False:
header_2_received = True
else:
# Since below, we reset headers once the full message is received, kind of pointless else
pass
else:
# If a non-header character is received, but we haven't identified the headers yet, then we're starting in the middle of a message or have lost the rest of our previous message
dat = []
header_1_received = False
header_2_received = False
except:
# struct.unpack likely failed; throw away the message and start again
header_1_received = False
header_2_received = False
dat = []
if(len(dat) == MESSAGE_LENGTH):
# Reset flags
#print(dat)
header_1_received = False
header_2_received = False
dat = []
readings += 1
except KeyboardInterrupt:
ser.close()
elapsed_time = time.time() - start_time
if readings > 0:
print("Number of readings: {}\nRun time: {}s\nAverage time per reading: {}s ({}ms)".format(readings,elapsed_time,elapsed_time/readings,(elapsed_time/readings)*1000))
C++
这是功能失调的 C++ 代码:
#include <string>
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include "serial/serial.h"
using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
int run(int argc, char **argv)
{
// Argument 1 is the serial port or enumerate flag
string port(argv[1]);
// Argument 2 is the baudrate
unsigned long baud = 0;
sscanf(argv[2], "%lu", &baud);
// port, baudrate, timeout in milliseconds
serial::Serial my_serial(port, baud, serial::Timeout::simpleTimeout(0.001));
cout << "Is the serial port open?";
if(my_serial.isOpen())
cout << " Yes." << endl;
else
cout << " No." << endl;
/* MY CUSTOM VARIABLES */
const float header = 112;
const int msg_size = 8;
int msg_index = 0;
float f; // the read float
float msg [msg_size] = { }; // the collected floats will be placed here, auto-filled with 0s
bool header_1_received = false;
bool header_2_received = false;
uint8_t *buffer = new uint8_t[sizeof(f)]; // buffer that will be converted to 32-bit float
int count = 0;
while (count < 1000) {
size_t number_of_bytes_read = my_serial.read(buffer, sizeof(f));
memcpy(&f, buffer, sizeof(f));
// Logic for adding new element to array
if (header_1_received and header_2_received){
msg[msg_index] = f;
msg_index += 1;
} else if (f == header) {
if (header_1_received == false){
header_1_received = true;
} else if (header_2_received == false){
header_2_received = true;
} else {
// Do nothing
}
} else {
// A non-header character was received, but headers are also not identified;
// Throw partial message away and restart
std::fill_n(msg, msg_size, 0); // Fill with zeroes
msg_index = 0;
header_1_received = false;
header_2_received = false;
}
// Check to see if message is full
if(msg_index == msg_size){
cout << "Msg: [";
for (int i = 0; i < msg_size; i += 1){
cout << msg[i] << ",";
}
cout << "]" << endl;
// Reset flags
header_1_received = false;
header_2_received = false;
std::fill_n(msg, msg_size, 0);
msg_index = 0;
}
count += 1;
}
return 0;
}
int main(int argc, char **argv) {
try {
return run(argc, argv);
} catch (exception &e) {
cerr << "Unhandled Exception: " << e.what() << endl;
}
}
可以找到 C++ 库 here, and the documentation on the read method here。据我了解,他的 read
方法将请求的字节数(如果可用)写入缓冲区;有来自其他设备的持续传入字节流,所以我不认为这是问题所在。
预期结果
Python3 脚本正常运行并输出以下内容:
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
(应该是两个非常小的数字,后面跟着大约-9.81,然后是5个零)。
实际结果
可以通过 运行 以下 command:
构建和执行 C++ 程序
g++ serial_example.cc -lserial -L ../build/devel/lib -I../include -o test_serial
LD_LIBRARY_PATH=`pwd`/../build/devel/lib ./test_serial
并输出以下内容:
[112,112,112,112,112,112,112,112,]
[112,-9.82691,-9.82691,-9.82691,-9.82691,-9.82691,-9.82691,0,]
[112,112,112,112,-9.82691,-9.82691,-9.82691,-9.82691,]
[112,112,112,112,112,112,112,112,]
如果我添加以下行
cout << "Float extracted from buffer: " << f << endl;
然后它输出它从读取操作重建的每个浮点数,导致 mish-mash 9.81、112 和 0。
问题
我的 C++ 程序出了什么问题导致它读取 bytes/float 与 Python 程序不同,如果库有问题,有什么替代方法或库可供读取C++ 中的串行消息?
编辑
在与@Barmar 和@Gaspa79 进行一些故障排除后,库的 read()
方法读取的字节数似乎不一致。我会尝试 re-writing 我的程序并留下新版本作为答案。
在验证转换确实正确后,我们意识到 OP 从未真正检查过 number_of_bytes_read 变量,并且底层库出于某种原因正在读取不同数量的字节。
总结
我有两个程序;一个用 Python3 编写,另一个用 C++ 编写。两者执行相同的任务;从串行端口读取,过滤掉两个 header 浮点数,并打印剩余的消息。 Python 脚本正常工作(请参阅下面的输出以获取正确的数字); C++ 的,使用 serial 库,没有,我不明白为什么。 (运行 Raspberry Pi 4,Raspbian 克星)。
为了避免有人阅读整篇文章;如果我决定使用这个库进行串行读取是错误的,我怎样才能正确地从 C++ 中的串行端口读取?
我试过的
我是 C++ 的新手,所以也许我找错了地方,但我找不到一个普遍接受的用于从串口读取的库,所以我选择了最有用的库github (serial) 上的星星。
This 答案给出了 windows 的示例和指向几个库的链接,但是它们要么是为了与 windows 一起使用,要么是在 C 中,而不是在 C++ 中。
我的代码
Python
这是功能齐全的 Python 代码:
import serial
import struct
import time
PORT_NUMBER = '/dev/ttyACM0'
BAUDRATE = 115200
MESSAGE_LENGTH = 8
HEADER_NUMBER = float(112)
header_1_received = False # Has the first header byte been received
header_2_received = False # Has the second header byte been received
dat = [] # The actual message
# Open serial port
ser = serial.Serial(
port=PORT_NUMBER,
baudrate=BAUDRATE,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=0.001)
ser.isOpen()
readings = 0
print('Receive data from Pixhawk using 2 header floats and {} message floats (32-bit) \nIf you wish to close the program, hit \"Ctrl+C\" on your keyboard and it (should) shut down gracefully.'.format(MESSAGE_LENGTH))
start_time = time.time() # Start time for the program
try:
# Main loop
while (True):
# Read 4 bytes (32-bits) to get a full float number
buffer = ser.read(4)
# Only proceed if the buffer is not empty (an empty buffer is b'')
if buffer != b'':
# Since struct.unpack() returns a tuple, we only grab the first element
try:
new_dat = struct.unpack("f",buffer)[0]
if header_1_received==True and header_2_received==True:
dat.append(new_dat)
elif new_dat == HEADER_NUMBER:
# We found a header single; treat it
if header_1_received == False:
header_1_received = True
elif header_2_received == False:
header_2_received = True
else:
# Since below, we reset headers once the full message is received, kind of pointless else
pass
else:
# If a non-header character is received, but we haven't identified the headers yet, then we're starting in the middle of a message or have lost the rest of our previous message
dat = []
header_1_received = False
header_2_received = False
except:
# struct.unpack likely failed; throw away the message and start again
header_1_received = False
header_2_received = False
dat = []
if(len(dat) == MESSAGE_LENGTH):
# Reset flags
#print(dat)
header_1_received = False
header_2_received = False
dat = []
readings += 1
except KeyboardInterrupt:
ser.close()
elapsed_time = time.time() - start_time
if readings > 0:
print("Number of readings: {}\nRun time: {}s\nAverage time per reading: {}s ({}ms)".format(readings,elapsed_time,elapsed_time/readings,(elapsed_time/readings)*1000))
C++
这是功能失调的 C++ 代码:
#include <string>
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include "serial/serial.h"
using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;
int run(int argc, char **argv)
{
// Argument 1 is the serial port or enumerate flag
string port(argv[1]);
// Argument 2 is the baudrate
unsigned long baud = 0;
sscanf(argv[2], "%lu", &baud);
// port, baudrate, timeout in milliseconds
serial::Serial my_serial(port, baud, serial::Timeout::simpleTimeout(0.001));
cout << "Is the serial port open?";
if(my_serial.isOpen())
cout << " Yes." << endl;
else
cout << " No." << endl;
/* MY CUSTOM VARIABLES */
const float header = 112;
const int msg_size = 8;
int msg_index = 0;
float f; // the read float
float msg [msg_size] = { }; // the collected floats will be placed here, auto-filled with 0s
bool header_1_received = false;
bool header_2_received = false;
uint8_t *buffer = new uint8_t[sizeof(f)]; // buffer that will be converted to 32-bit float
int count = 0;
while (count < 1000) {
size_t number_of_bytes_read = my_serial.read(buffer, sizeof(f));
memcpy(&f, buffer, sizeof(f));
// Logic for adding new element to array
if (header_1_received and header_2_received){
msg[msg_index] = f;
msg_index += 1;
} else if (f == header) {
if (header_1_received == false){
header_1_received = true;
} else if (header_2_received == false){
header_2_received = true;
} else {
// Do nothing
}
} else {
// A non-header character was received, but headers are also not identified;
// Throw partial message away and restart
std::fill_n(msg, msg_size, 0); // Fill with zeroes
msg_index = 0;
header_1_received = false;
header_2_received = false;
}
// Check to see if message is full
if(msg_index == msg_size){
cout << "Msg: [";
for (int i = 0; i < msg_size; i += 1){
cout << msg[i] << ",";
}
cout << "]" << endl;
// Reset flags
header_1_received = false;
header_2_received = false;
std::fill_n(msg, msg_size, 0);
msg_index = 0;
}
count += 1;
}
return 0;
}
int main(int argc, char **argv) {
try {
return run(argc, argv);
} catch (exception &e) {
cerr << "Unhandled Exception: " << e.what() << endl;
}
}
可以找到 C++ 库 here, and the documentation on the read method here。据我了解,他的 read
方法将请求的字节数(如果可用)写入缓冲区;有来自其他设备的持续传入字节流,所以我不认为这是问题所在。
预期结果
Python3 脚本正常运行并输出以下内容:
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.08539174497127533, 0.17273111641407013, -9.816835403442383, 0.0, 0.0, 0.0, 0.0, 0.0]
(应该是两个非常小的数字,后面跟着大约-9.81,然后是5个零)。
实际结果
可以通过 运行 以下 command:
构建和执行 C++ 程序g++ serial_example.cc -lserial -L ../build/devel/lib -I../include -o test_serial
LD_LIBRARY_PATH=`pwd`/../build/devel/lib ./test_serial
并输出以下内容:
[112,112,112,112,112,112,112,112,]
[112,-9.82691,-9.82691,-9.82691,-9.82691,-9.82691,-9.82691,0,]
[112,112,112,112,-9.82691,-9.82691,-9.82691,-9.82691,]
[112,112,112,112,112,112,112,112,]
如果我添加以下行
cout << "Float extracted from buffer: " << f << endl;
然后它输出它从读取操作重建的每个浮点数,导致 mish-mash 9.81、112 和 0。
问题
我的 C++ 程序出了什么问题导致它读取 bytes/float 与 Python 程序不同,如果库有问题,有什么替代方法或库可供读取C++ 中的串行消息?
编辑
在与@Barmar 和@Gaspa79 进行一些故障排除后,库的 read()
方法读取的字节数似乎不一致。我会尝试 re-writing 我的程序并留下新版本作为答案。
在验证转换确实正确后,我们意识到 OP 从未真正检查过 number_of_bytes_read 变量,并且底层库出于某种原因正在读取不同数量的字节。