Sunday, June 23, 2013

Connecting Raspberry Pi and Arduino. Software

In my previous post I described how to make hardware connection between Raspberry Pi and Arduino. Now I will describe the software part. I will describe how to make software connection from scratch pretty easily. And I will use some C and C#.

Raspberry Pi

I use Arch Linux on my Raspberry Pi (more lightweight and appropriate distributive for this computer to my mind). But I2C drivers work the same way on other distributives, so, only some system specific commands could be different.

1. Update your system. I2C drivers were released in Fall 2012, so if your system is old enough do this
$ pacman -Syu

2. Load I2C kernel module:
$ modprobe i2c-dev
To load the module automatically on boot, create file /etc/modules-load.d/i2c.conf and add line i2c-dev to the file.

3. Check I2C works. Run
$ i2cdetect 1
Where 1 is the number of I2C bus. The command should output table with addressed of all connected devices. But for now that table is empty as far as we haven't initialized the Arduino as an I2C slave.

Arduino

To work with I2C on Arduino you can use the standard library Wire. The code below initializes the I2C bus, reads sending data and sends data back.
#include <Wire.h>

void setup()
{
  Serial.begin(115200);          // start serial for output
  Wire.begin(42);                // join i2c bus with address #42
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData); 
}

void loop()
{
  delay(100);
}

// callback for received data
void receiveData(int byteCount) 
{
  while(Wire.available())       // loop through all but the last
  {
    char c = Wire.read();       // receive byte as a character
    Serial.print(c);            // print the character
  }
}

// callback for sending data
void sendData()
{ 
  Wire.write (79);
}
After uploading this code to Arduino we can get back to the Raspberry Pi.

Raspberry Pi again

Now, after initializing the Arduino, i2cdetect command should show you that a device with address 42 is connected to the I2C bus. If that works, it's time to send some data from Raspberry Pi. I'm a dotNET guy, and I will use C# and Mono. And to work with I2C I use my library RPi.I2C.Net. The code below is the simple application to send and read data from the Arduino.
static void Main(string[] args)
{
 using (var bus = RPi.I2C.Net.I2CBus.Open("/dev/i2c-1"))
 {
  bus.WriteBytes(42, new byte[] { 49, 50, 51 });
  byte[] res = bus.ReadBytes(42, 1);
  Console.WriteLine(res[0]);
 }
}
Now it's time to create more complex communication.

1 comment:

  1. I'd like to say. Your work here is absolutely awesome. Seriously. I will be using your library for a number of projects and you have made it that much easier for me.

    ReplyDelete