我想将四个字节合并为一个数字以进行串行传输
I want to merge four bytes into one digit for serial transmission
我想使用 python 将长值发送到运行 c++ 的 arduino 板。串行通信将 4 个字节的数字分解并逐字节发送。当我尝试在后端重新组装它们时,我只得到一个 2 字节的有效数字,而不是我发送的 4 个字节。
这是python代码发送指令。
pos1 = int(input("pos1: "))
pos2 = int(input("pos2: "))
data = struct.pack('<ll', pos1, pos2)
ser.write(data)
这是解析它读取的字节的arduino代码。
if(Serial.available()>0){
size_t numbytes = Serial.readBytes(data, 8);
for(int i=0; i<8; i++){
Serial.println(data[i], HEX);
}
pos1 = readfourbytes(data[0], data[1], data[2], data[3]);
pos2 = readfourbytes(data[4], data[5], data[6], data[7]);
Serial.println(pos1);
Serial.println(pos2);
}
long readfourbytes(byte fourthbyte, byte thirdbyte, byte thirdbyte, byte firstbyte){
long result = (firstbyte << 24) + (secondbyte << 16) + (thirdbyte << 8) + fourthbyte;
return result;
}
我想这意味着 arduino 是小端序?我的问题是读取的第二个位置值完全关闭。python代码似乎是问题所在,但我不知道为什么。当我为两者发送 int 值 100 时,我得到的输出为
B'd\x00\x00\x00d\x00\x00\x00'
从 Python 代码作为在数据变量中发送的二进制文件。但是从 arduino 中,我收到:
64
0
0
0
6D
阿拉伯数字
0
0
100
621
因此,我发送的内容和接收的内容之间存在脱节。波特率是一样的,我知道没有其他明显的错误。
>所有表达式(<any>byte << <bits>)
都被评估为int
,在arduino上似乎是16位。将<any>byte
投射到long
中,你就完成了。
long readfourbytes(byte fourthbyte, byte thirdbyte, byte thirdbyte, byte firstbyte){
long result = ((long)firstbyte << 24) + ((long)secondbyte << 16) + (thirdbyte << 8) + fourthbyte;
return result;
}
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 我想做一个彼此不同但重复出现的数字
- 如何检查一个c++字符串中有多少相同的字符/数字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- CIN 仅在输入非数字值时跳过下一个 CIN
- 以C++输出一个数字三角形
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 将数字提高到一个巨大的指数
- 反转一个数字程序不起作用,为什么?
- 使用带有一个参数函数的递归找到数字的平方
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作