Wednesday, March 13, 2013

Sending Data from an Arduino to a Raspberry Pi Using I2C

On my Arduino blog I posted the portion of this example for the Arduino Leonardo. See that post for noes on the actual connections between the Arduino and the Raspberry Pi. Below is the example Python 2 code that runs on the Raspberry Pi.


Code:


This code assumes that you have enabled I2C on the Raspberry Pi and installed the SMBus module for Python (which provides I2C support).


import smbus
import time
import struct

bus = smbus.SMBus(1)
address = 0x03

while True:
    try:
        data = bus.read_i2c_block_data(address, 0);
    except:
        print "Error getting data\n"
        continue
    # Example uses 4 sensors. 
    # Each float from the Arduino is 4 bytes long.
    for i in range(0, 4):
        bytes = data[4*i:4*i+4]
        # Python 2 struct.unpack takes the data to be unpacked 
        # in string format, so the bytes need to be joined
        # together first
        print struct.unpack('f', "".join(map(chr, bytes)))[0]
    print
    time.sleep(5);


2 comments:

  1. can you tell me the meaning of value 0 in line: data = bus.read_i2c_block_data(address, 0); i want to know why you use 0? why don't use another value; example 1 or 2 or 3...?

    ReplyDelete
    Replies
    1. The 0 is just an empty command. The command just reads data that is waiting to be read. There is no command sent to cause the data to be sent.

      --Brad

      Delete