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

时间:2016-10-22 20:28:19

标签: 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(我的);不会工作所以我想知道我是否有办法做到这一点?也许我需要完全尝试其他方法?只要我能将结构传输到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)

1 个答案:

答案 0 :(得分:2)

您可以使用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)