Saturday, December 13, 2014

Communication between Raspberry Pi and Arduino via I2C, using Python.

This exercise implement communiation between Raspberry Pi and Arduino using I2C. Here Raspberry Pi, programmed with Python, act as I2C host and Arduino Uno act as slave.

Download the sketch (I2CSlave.ino) to Arduino Uno. It receive I2C data, turn ON LED if 0x00 received, turn OFF LED if 0x01 received.
#include <Wire.h>

#define LED_PIN 13

byte slave_address = 7;
byte CMD_ON = 0x00;
byte CMD_OFF = 0x01;

void setup() {
  // Start I2C Bus as Slave
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);  

}

void loop() {

}

void receiveEvent(int howMany) {
  byte cmd = Wire.read();
  if (cmd == CMD_ON){
    digitalWrite(LED_PIN, HIGH);
  }else if(cmd == CMD_OFF){
    digitalWrite(LED_PIN, LOW);
  }
}

Prepare on Raspberry Pi, refer to last post "Enable I2C and install tools on Raspberry Pi".

Connection between Raspberry Pi and Arduino.


Then you can varify the I2C connection using i2cdetect command. Refer to below video, the I2C device with address 07 match with slave_address = 7 defined in Arduino sketch.


On Raspberry Pi, run the command to install smbus for Python, in order to use I2C bus.
sudo apt-get install python-smbus


Now create a Python program (i2c_uno.py), act as I2C master to write series of data to Arduino Uno, to turn ON/OFF the LED on Arduino Uno. Where address = 0x07 have to match with the slave_address in Arduino side.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
bus = smbus.SMBus(1)

# I2C address of Arduino Slave
address = 0x07

LEDst = [0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01]
for s in LEDst:
    bus.write_byte(address, s)
    time.sleep(1)

Finally, run with command:
$ sudo python i2c_uno.py



Next:
Raspberry Pi send block of data to Arduino using I2C
Write block and read byte
Wire.write() multi-byte from Arduino requestEvent


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

No comments: