Reputation: 70
I'm tinkering with my RaspberryPi and my Arduino to send some text over I2C. I got it working so far but there is a number appearing which shouldn't exist.
I'm sending "Hello" converting it to an int array and sending it over 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
The leading 0 is intentional but the 5 shouldn't exist at all!
The (shortened) code I'm running on the 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);
}
The exact output I'm getting:
[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"
The code running on the 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)
Upvotes: 2
Views: 973
Reputation: 33223
Just from the values shown it is likely to be the number of chars or bytes being sent in the string part of the transmission. "Hello" has 5 bytes in ASCII representation.
If you look at the description of the smbus protocol in the section for the write_block_data
command it documents that an 8 bit Count is sent after the command byte which gives the length of the Data block.
SMBus Block Write: i2c_smbus_write_block_data()
The opposite of the Block Read command, this writes up to 32 bytes to a device, to a designated register that is specified through the Comm byte. The amount of data is specified in the Count byte.
S Addr Wr [A] Comm [A] Count [A] Data [A] Data [A] ... [A] Data [A] P
Upvotes: 1