【发布时间】:2015-04-26 03:13:11
【问题描述】:
我正在尝试通过我的 Arduino (C++) 的串行 USB 接口向 Raspberry Pi (Python) 发送消息。
在 Arduino 方面,我定义了一个结构,然后将其复制到一个 char[] 中。结构的最后一部分包含我想使用 CRC32 计算的校验和。我将结构复制到临时 char 数组 -4 字节中以去除校验和字段。然后使用临时数组计算校验和,并将结果添加到结构中。然后将该结构复制到通过串行连接发送的 byteMsg 中。
在树莓端我做相反的事情,我接收字节串并计算消息的校验和 - 4 个字节。然后解压字节串并比较接收和计算的校验和,但不幸的是失败了。
为了调试,我比较了 python 和 arduino 上的 crc32 检查字符串“Hello World”,它们生成了相同的校验和,所以库似乎没有问题。覆盆子还能够很好地解码消息的其余部分,因此将数据解包到变量中似乎也可以。
任何帮助将不胜感激。
Python 代码:
def unpackMessage(self, message):
""" Processes a received byte string from the arduino """
# Unpack the received message into struct
(messageID, acknowledgeID, module, commandType,
data, recvChecksum) = struct.unpack('<LLBBLL', message)
# Calculate the checksum of the recv message minus the last 4
# bytes that contain the sent checksum
calcChecksum = crc32(message[:-4])
if recvChecksum == calcChecksum:
print "Checksum checks out"
Aruino crc32 库取自http://excamera.com/sphinx/article-crc.html
crc32.h
#include <avr/pgmspace.h>
static PROGMEM prog_uint32_t crc_table[16] = {
0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
};
unsigned long crc_update(unsigned long crc, byte data)
{
byte tbl_idx;
tbl_idx = crc ^ (data >> (0 * 4));
crc = pgm_read_dword_near(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
tbl_idx = crc ^ (data >> (1 * 4));
crc = pgm_read_dword_near(crc_table + (tbl_idx & 0x0f)) ^ (crc >> 4);
return crc;
}
unsigned long crc_string(char *s)
{
unsigned long crc = ~0L;
while (*s)
crc = crc_update(crc, *s++);
crc = ~crc;
return crc;
}
主要的 Arduino 草图
struct message_t {
unsigned long messageID;
unsigned long acknowledgeID;
byte module;
byte commandType;
unsigned long data;
unsigned long checksum;
};
void sendMessage(message_t &msg)
{
// Set the messageID
msg.messageID = 10;
msg.checksum = 0;
// Copy the message minus the checksum into a char*
// Then perform the checksum on the message and copy
// the full msg into byteMsg
char byteMsgForCrc32[sizeof(msg)-4];
memcpy(byteMsgForCrc32, &msg, sizeof(msg)-4);
msg.checksum = crc_string(byteMsgForCrc32);
char byteMsg[sizeof(msg)];
memcpy(byteMsg, &msg, sizeof(msg));
Serial.write(byteMsg, sizeof(byteMsg));
void loop() {
message_t msg;
msg.module = 0x31;
msg.commandType = 0x64;
msg.acknowledgeID = 0;
msg.data = 10;
sendMessage(msg);
亲切的问候, 蒂兹恩
【问题讨论】:
标签: python c++ arduino raspberry-pi crc32