错误的数据传输I2C RasPi-> Arduino

时间:2015-08-25 11:39:53

标签: python arduino raspberry-pi i2c arduino-uno

我正在修改我的RaspberryPi和我的Arduino以通过I2C发送一些文本。到目前为止,我已经开始工作了,但是有一些不应该存在。

我发送"你好"将其转换为int数组并通过I2C发送。

['H','e','l','l','o'] => [72,97,108,108,111] // This should be the result
['H','e','l','l','o'] => [0, 5, 72, 101, 108, 108, 111] // This is what i get

领先的0是故意的,但5根本不存在!

我在Arduino上运行的(缩短的)代码:

void setup() {
  Serial.begin(9600); // start serial for output
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveData);  
  Serial.println("Ready!");
}

receiveData(int byteCount) {
    int i;

    // Iterate through the byte packets
    for(i = 0; Wire.available(); i++) { 
        number = Wire.read();

        if(i != 0) {  // Ignore the first byte
            text[i-1] = (char)number;
        }

        // Output number, byteCount, and i over the serial bus
    }

    Serial.print("Result: ");
    Serial.println(text);
}

我得到的确切输出:

[CMD]data received: 0, 2char: , byteCount: 7, Iteration: 0 //The cmd byte
data received: 5, 2char: , byteCount: 7, Iteration: 1
data received: 72, 2char: H, byteCount: 7, Iteration: 2
data received: 101, 2char: e, byteCount: 7, Iteration: 3
data received: 108, 2char: l, byteCount: 7, Iteration: 4
data received: 108, 2char: l, byteCount: 7, Iteration: 5
data received: 111, 2char: o, byteCount: 7, Iteration: 6
Result: "Hello"

RaspberryPi(Python)上运行的代码:

import smbus
import time

# Initiate the SMBus on device 1
bus = smbus.SMBus(1)

# The address of the Arduino
address = 0x04

chars = [] # The character/int array
test = "Hello" # The test text

# Split up the string in individual chars, 
# convert them to int and add them to the array
for c in test:
    chars.append(ord(c))

# send the data... the 0 is the cmd byte! The function accepts an int array
bus.write_block_data(address, 0, chars) 

1 个答案:

答案 0 :(得分:1)

仅从显示的值中,它可能是在传输的字符串部分中发送的字符或字节的数量。 "你好" ASCII表示中有5个字节。

如果查看write_block_data命令部分中smbus protocol的描述,它会记录在命令字节后发送8位计数,该字节给出数据块的长度。 / p>

  

SMBus块写入:i2c_smbus_write_block_data()

     

与Block Read命令相反,它最多写入32个字节   一个设备,通过该指定的指定寄存器   通讯字节。数据量在Count字节中指定。

     

S Addr Wr [A] Comm [A] 计数 [A]数据[A]数据[A] ... [A]数据[A] P