如何通过i2c将Arduino结构传递给Raspberry Pi?
对于我的Arduino,我有一个结构:如何通过i2c将Arduino结构传递给Raspberry Pi?,arduino,i2c,Arduino,I2c,对于我的Arduino,我有一个结构: int temp; struct dataStruct { int Data; int Data2; int Data3; int Data4; int Data5; } my; void setup() { Wire.begin(SLAVE_ADDRESS); Wire.onReceive(receiveData); Wire.onRequest(sendData); }
int temp;
struct dataStruct {
int Data;
int Data2;
int Data3;
int Data4;
int Data5;
} my;
void setup() {
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
void loop(){
delay(1000)
}
void receiveData(){
while(Wire.available){
temp = Wire.read();
}
}
void sendData(){
Wire.write((byte *)&my, sizeof(my));
}
我想通过i2c通过Wire.write函数将结构传递给我的Raspberry Pi。我意识到只要试一下电线就行了;不会工作,所以我想知道是否有一种方法,我可以去做这件事?也许我需要尝试一种完全不同的方法?我愿意尝试其他方法,只要我能将结构传输到Raspberry Pi
下面是我的Python代码:
import socket
import os
import random
import time
import smbus
import struct
bus = smbus.SMBus(1)
address = 0x04
temp = bytes([0x00, 0x00, 0x00, 0x00, 0x00])
the_struct = [0, 0, 0, 0, 0]
def writeNumber(value):
bus.write_byte(address, value)
return -1
def readNumber():
number = bus.read_byte(address)
return number
while True:
temp = readNumber()
the_struct = struct.unpack('5h', temp)
print(the_struct)
time.sleep(1)
您可以使用
Wire.write((byte*)&my,sizeof(my))
写入RPi。要读取数据,可以使用struct
模块将结构解压为元组,如下所示:
import struct
#assuming you've recved the struct over I2C into a bytes object named 'data'
the_struct = struct.unpack('5h', data)
结构现在保存原始结构中的5个整数
编辑
首先,0x04是保留地址之一。改为尝试0x15;0x08以上的任何内容(几乎)都可以
您正在读取一个字节,然后试图将该字节解压为5个整数。相反,您应该读取10个字节,将它们逐个保存到bytearray
中,然后按照前面所示将它们解压缩。将您的readNumber()
替换为:
def read_block(num_bytes):
vals = bus.read_i2c_block_data(address, num_bytes)
return vals
while True:
temp = read_block(10) # 10 is the number of bytes you want to read
the_struct = struct.unpack('5h', temp)
print(the_struct)
time.sleep(1)
我认为序列化是你想要的。请注意,架构可能不同到足以发送原始内存(这将是一个坏主意)。好的,谢谢,我将研究串行通信。实际上,这不是我真正的意思。即。串行通信可能会很好,这取决于你的使用。啊,好吧,我开始研究这个问题。看起来Wire.write函数能够发送字节数组,我已经完成了。但是现在我的问题是在Pi上将字节数组转换成整数数组。RPi和Arduino都使用了小的endianess,所以我不认为有任何奇怪的转换需要确保。您应该明确给出数据、数据2等的大小,以避免任何混淆-即两端的int16_t或int32_t。我尝试过Wire.write(&my,sizeof(my))并获得多个错误。看来我的结构是错误的数据类型?但是,如果我声明,例如,byte var={1,2},我可以用Wire.write(var,2)成功地传递它。感谢@TisteAndii,我能够获得要写入的数据。现在,当我在Python代码中放入'the_struct=struct.unpack('5h',data')时,我得到了typeerror:'int'不支持缓冲区接口。我忘了提到:类型双关不仅是UB,而且结构填充也可能使发送的数据不可靠!您应该避免使用此解决方案。无需担心-使用uint8\u t*读取结构实际上是合法的。但填充物可能仍然是一个问题。