Wednesday, 17 April 2013

RPi / Arduino - interfacing.

Right. - So my issue is that I wrote a system on the Pi using Python with an HC-SR04 (ultrasonic distance) sensor. - This needs accurate measurement of time to give meaningful distance, and because the Pi is scheduled, multi-tasking OS, this is nigh on impossible to do, and the variance in distance measured was some 30cm over about 1.5M over a 24 hour period of monitoring.

Some tinkering with an Arduino seems to suggest that this is much more accurate in it's timing as you'd expect because it's not multi-tasking.....  So - plan is to implement distance measure on the Arduino, and use the Pi for the higher level bits. (tweet / mail / cosm etc).

1. - sudo apt-get install arduino.
2. - Unblacklist i2c

pi@raspberrypi ~ $ cat /etc/modprobe.d/raspi-blacklist.conf
# blacklist spi and i2c by default (many users don't need them)

##blacklist spi-bcm2708
##blacklist i2c-bcm2708

pi@raspberrypi ~ $ sudo modprobe i2c-bcm2708

Add i2c-dev to /etc/modules

sudo modprobe i2c-dev.

sudo apt-get install i2c-tools

sudo adduser pi i2c

sudo i2cdetect -y 0

No errors, so this seems to be working.

sudo apt-get install python-smbus


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

while True:
        data = ""
        ch = ""
        while ch != 'x':
                ch = chr(bus.read_byte(address));
                print ch;
                print "no data..."
                time.sleep(1) # give it chance to wake up / reboot, whatever.
            if ch != 'x':
                    data += ch;
        print data
        ch = ""

Corresponding sketch on the arduino for distance with HC-SR04 sensor:-

#include <Wire.h>
#define SLAVE_ADDRESS 0x2A
#define trigPin 6
#define echoPin 7

int led = 13;
char data[] = "The quick brown fog jumped over the lazy dogx";
long distance = 42;
long duration;
int index = 0;

void setup() {
    // initialize i2c as slave
    pinMode(led, OUTPUT);
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);

void loop() {
  digitalWrite(trigPin, LOW);  // Trig needs to go high on 10us pulse
  delayMicroseconds(2); // wait....
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // Trig pin pulse time.
  digitalWrite(trigPin, LOW);  // Now, we time to echo.
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  ltoa(distance, data, 10);
  strcat(data, "x");

// callback for sending data
void sendData() {
    digitalWrite(led, HIGH);
    if (index >= strlen(data)) {
         index = 0;
         digitalWrite(led, LOW);


No comments:

Post a Comment

Note: only a member of this blog may post a comment.