I am building a Web Controlled Robot and have been testing i2c communication between my RPi and an Arduino Nano.
I have had some success with webiopi and pigpio cotrolling servos over a web page connected directly to the Pi and now I want to add an Arduino Nano into the mix.
The Nano will be connected via i2c and before I try it over webiopi (web page) I thought Id' get it working first from a Python IDLE session.
I have successfully connected the Pi and the Nano over i2c and my test program (borrowed from Oscar Laing) is working.
Couple of problems:
1. When I enter 1 the LED illuminates but when I enter another number it does not go off?
2. If I enter the same number twice in a row Python exits and complains of a EOF (sorry not got the error in front of me).
Also I had to force this to use Python 2 because Python 3 complained of "no module named smbus, is there a version for Python 3?
Here is the Python code:
Code: Select all
#!/usr/bin/env python
import smbus
import time
# For RPi version 1 use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)
# This is the address we setup in the Arduino Program
address = 0x04
def writeNumber(value):
bus.write_byte(address, value)
# bus.write_byte_data(address, 0, value)
return -1
def readNumber():
number = bus.read_byte(address)
# number = bus.read_byte_data(address, 1)
return number
while True:
var = input("Enter 1 - 9: ")
if not var:
continue
writeNumber(var)
print("RPI: Hi Arduino, I sent you ", var)
# sleep one second
time.sleep(1)
number = readNumber()
print("Arduino: Hey RPI, I received a digit ", number)
print()Code: Select all
// Arduino Pin A5 to RPi SDA
// Arduino Pin A6 to RPi SCL
// Inspiration from Ocra Laing's Blog http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600); // Start serial for output
Wire.begin(SLAVE_ADDRESS); // Initialise i2c as slave
// Define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
Serial.println("Ready!");
}
void loop() {
delay(100);
}
// Callback for received data
void receiveData(int byteCount) {
while(Wire.available()) {
number = Wire.read();
Serial.println("data received: ");
Serial.println(number);
if (number == 1){
if (state == 0){
digitalWrite(13, HIGH); // turn the LED on
state = 1;
}
else{
digitalWrite(13, LOW); // turn the LED off
state = 0;
}
}
}
}
// Callback for sending data
void sendData() {
Wire.write(number);
}
