I am trying to connect an Arduino Uno with my Raspberry using the i2c bus, based on the tutorial given here, sending only one byte from RPi to Arduino and back. I was able to implement this and it works fine.
I needed to transfer more than a byte of data, so I referred to this page and tried to implement the given solution with python 3.4.2. However when I implement the solution, it gives me following error:
>>>
[45, 0, 25, 2, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
Traceback (most recent call last):
File "/home/pi/codeSampleMaster2.py", line 15, in <module>
number = readLong()
File "/home/pi/codeSampleMaster2.py", line 10, in readLong
n = struct.unpack('<l',(''.join([chr(i) for i in block[:4]])))[0]
TypeError: 'str' does not support the buffer interface
The data in the square bracket is what I received as part of block read. What I require is to be able to extract 45002502 as part of my program.
Please guide me as to where I might have made a mistake. Im fairly new to working with python and Rasp Pi.
Arduino Code:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
int senseLeft = A0; // Left side distance sensor input pin.
long senseLeftVal = 0; // Variable to store the Left side sensor value.
void setup() {
Serial.begin (9600); // start serial for output
Wire.begin(SLAVE_ADDRESS);
Wire.onRequest(requestEvent); // register event
Serial.println("Ready!");
}
void loop() {
// Serial.println(senseLeftVal);
delay(1);
}
void requestEvent()
{
senseLeftVal = analogRead(senseLeft);
Wire.write((const uint8_t*)&senseLeftVal, sizeof(long));
Serial.println(senseLeftVal);
}
Rasp Pi Code:
import smbus
import time
import struct
bus = smbus.SMBus(1)
address = 0x04
def readLong():
block = bus.read_i2c_block_data(address,0)
print(block)
n = struct.unpack('<l',(''.join([chr(i) for i in block[:4]])))[0]
return n
while True:
time.sleep(1)
number = readLong()
print("Arduino: ", number)
n = block[0] | block[1] << 8 | block[2] <<16 | block[3] << 24
which should give the correct answer. – joan Oct 6 '16 at 9:44block[0] | block[1] << 8
andblock[2] | block[3] << 8
. Any additional byte changes the output to random numbers. – Parth D Oct 6 '16 at 18:21