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).
http://neophob.com/2013/04/i2c-communication-between-a-rpi-and-a-arduino/
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.
From - http://stackoverflow.com/questions/14420372/how-to-read-data-from-arduino-with-raspberry-pi-with-i2c
sudo apt-get install python-smbus
#!/usr/bin/python
import smbus
import time
bus = smbus.SMBus(0)
address = 0x2a
while True:
data = ""
ch = ""
while ch != 'x':
try:
ch = chr(bus.read_byte(address));
print ch;
except:
print "no data..."
time.sleep(1) # give it chance to wake up / reboot, whatever.
if ch != 'x':
data += ch;
print data
ch = ""
time.sleep(1);
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
Wire.begin(SLAVE_ADDRESS);
Wire.onRequest(sendData);
pinMode(led, OUTPUT);
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
//Serial.println("Hello");
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");
//Serial.println(data);
delay(100);
}
// callback for sending data
void sendData() {
digitalWrite(led, HIGH);
Wire.write(data[index]);
++index;
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.