arduino - 如何通过 i2c 将 Arduino 结构体传递给 Raspberry Pi?

标签 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);
}

void loop(){
    delay(1000)
}

void receiveData(){
    while(Wire.available){
        temp = Wire.read();
    }
}

void sendData(){
    Wire.write((byte *)&my, sizeof(my));
}

我想通过 Wire.write 函数通过 i2c 将结构传递到我的 Raspberry Pi。我意识到只需尝试 Wire.write(my);不会起作用,所以我想知道是否有办法可以做到这一点?也许我需要尝试完全其他的方法?只要能把结构体传到树莓派上,我愿意尝试其他方式。

这也是我的 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)

the_struct 现在保存原始结构中的 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)

关于arduino - 如何通过 i2c 将 Arduino 结构体传递给 Raspberry Pi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196733/

相关文章:

C++ 模板类作为函数的参数

Linux I2C 内核驱动绑定(bind)

linux - 如何在 Linux 上模拟 I2C 设备?

linux - 升级特定的 Linux 内核子系统?

c - 如何转换温度传感器得到的值?

arduino - server.args() ESP8266 Arduino

c - 将 esp-32 摄像头流式传输到 YouTube 等 RTMP 服务器

delphi - 在 Delphi 中正确调用外部 dll?

arduino - 端口在 Arduino IDE 中处于非事件状态

python - blender 没有响应我的加速度计运动