How to connect Arduino Uno with Raspberry Pi using I²C

I am trying to send data via an I²C interface from Arduino Uno to Raspberry Pi using I²C. This was the code I used.

In Arduino:

#include <Wire.h> unsigned int watt; unsigned int watt1; byte watt2; byte watt3; void setup() { Wire.begin(30); Wire.onRequest(requestEvent); Serial.begin(9600); } void loop() { delay(100); int sensorValue = analogRead(A0); int sensorValue1 = analogRead(A1); watt = sensorValue * (5 / 1023) * 2857; watt1 = sensorValue1 * (5 / 1023) * 2857; watt2 = map(watt, 0, 4294967295, 0, 255); watt3 = map(watt1, 0, 4294967295, 0, 255); Serial.println(watt2); Serial.println(watt3); } void requestEvent() { Wire.write(watt2); delay(30); Wire.write(watt3); } 

And in Raspberry Pi:

 import smbus import time bus = smbus.SMBus(0) address = 0x1e while (1): watt=bus.read_byte_data(address,1) watt2=bus.read_byte_data(address,2) 

I got the following error.

Traceback (last last call):
File "/ home / pi / i 2ctest.py", line 8, in <module>
watt = bus.read_byte_data (address, 1)
IOError: error [Errno 5] I / O error

How to fix it? Also, are there alternatives for using I²C in Raspberry Pi besides the SMBus library?

+4
source share
1 answer

If you have a Raspberry Pi with board version 2.0, you need to use the I²C bus 1 and not bus 0, so you will need to change the bus number used. In this case, the line

 bus = smbus.SMBus(0) 

will become

 bus = smbus.SMBus(1) 

You can verify that the device is present on the bus using the i2cdetect program from the i2ctools package. Try

 i2cdetect 0 -y 

to find Arduino on bus 0. Run

 i2cdetect 1 -y 

look for it on bus 1. Of course, the Arduino program must work for it to work. It will also confirm that Arduino is present at the expected address.

You also need to make sure that you have the appropriate rights to use I²C, so start your Python program from an account that is a member of the i2c group.

+4
source

All Articles