Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data from Arduino with Raspberry Pi with I2C

I am trying to read data from an Arduino UNO to Raspberry Pi with the python smbus module. The only documentation I could find on the smbus module was here. I am not sure what the cmd means in the module. I can use the write to send data to the Arduino. I have written two simple programs one for read and one for write

The one for write

import smbus
b = smbus.SMBus(0)
while (0==0):
    var = input("Value to Write:")
    b.write_byte_data(0x10,0x00,int(var))

The one for read

import smbus
bus = smbus.SMBus(0)
var = bus.read_byte_data(0x10,0x00)
print(var)

The Arduino code is

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include <Wire.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int a = 7;

void setup() 
{ 
  Serial.begin(9600);
  lcd.begin(16,2);
  // define slave address (0x2A = 42)
  #define SLAVE_ADDRESS 0x10

  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData); 
}
void loop(){
}

// callback for received data
void receiveData(int byteCount) 
{
 Serial.println(byteCount);
  for (int i=0;i <= byteCount;i++){
  char c = Wire.read();
  Serial.println(c);
 }
}

// callback for sending data
void sendData()
{ 
  Wire.write(67);
  lcd.println("Send Data");
}

When I run the read program it returns "33" every time. The Arduino returns that the the sendData function is called.

I am using a Data Level Shifter and the description says it might be a little sluggish.

Has anyone gotten this to work?

like image 950
TheGreenToaster Avatar asked Jan 20 '13 00:01

TheGreenToaster


Video Answer


1 Answers

I managed to initiate a communication between an Arduino and a Raspberry Pi. The two are connected using two 5k pullup resistors (see this page). The arduino write a byte on the i2c bus for each request. On the Raspberry Pi, hello is printed every second.

Arduino code:

#include <Wire.h>
#define SLAVE_ADDRESS 0x2A

void setup() {
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);
    Wire.onRequest(sendData); 
}

void loop() {
}

char data[] = "hello";
int index = 0;

// callback for sending data
void sendData() { 
    Wire.write(data[index]);
    ++index;
    if (index >= 5) {
         index = 0;
    }
 }

Python code on the Raspberry Pi:

#!/usr/bin/python

import smbus
import time
bus = smbus.SMBus(1)
address = 0x2a

while True:
    data = ""
    for i in range(0, 5):
            data += chr(bus.read_byte(address));
    print data
    time.sleep(1);

On my Raspberry Pi, the i2c bus is 1. Use the command i2c-detect -y 0 or i2c-detect -y 1 to verify if your Raspberry Pi detect your Arduino.

like image 174
StebQC Avatar answered Oct 11 '22 13:10

StebQC