User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

i2c Serial Communication RPi and Arduino via WebIOPi

Mon Aug 03, 2015 5:06 pm

Hi;

I can successfully communicate between my RPi and an Arduino Nano via i2c Serial to turn on an LED connected to the Nano from a Python script running on the RPi.
I have can successfully control a couple of servos connected to the RPi GPIO using WebIOPi but cannot control anyting connected to the Nano.
I now want to be able to do this from a web page using WebIOPi, this is where I am now stuck.
The problem appears to be that my working code uses the Python 2 'smbus' library which is not available in WebIOPi?

Here's my python code:

Code: Select all

# Prior to running this program you must start the pigpio daemon by
# entering 'sudo pigpiod' at the command prompt
# To start webiopi enter 'sudo webiopi -d -c /etc/webiopi/config' at the command prompt

#!/usr/bin/env python

import webiopi
import smbus
import time
import pigpio
pi = pigpio.pi()

bus = smbus.SMBus(1)
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

# Start the webiopi server
# server = webiopi.Server(port=8000, login="Hammerstein", password="Hammerstein"

# Define functions

#@webiopi.macro
def cam_pan_left():
    pi.set_servo_pulsewidth(23, 1900)
    time.sleep(1)
    pi.set_servo_pulsewidth(23, 0)

#@webiopi.macro
def cam_pan_right():
    pi.set_servo_pulsewidth(23, 1100) 
    time.sleep(1)
    pi.set_servo_pulsewidth(23, 0)

#@webiopi.macro
def cam_pan_centre():
    pi.set_servo_pulsewidth(23, 1500)
    time.sleep(1)	
    pi.set_servo_pulsewidth(23, 0)

#@webiopi.macro
def cam_tilt_up():
    pi.set_servo_pulsewidth(24, 1100)	
    time.sleep(1)
    pi.set_servo_pulsewidth(24, 0)

#@webiopi.macro
def cam_tilt_down():
    pi.set_servo_pulsewidth(24, 1900)	
    time.sleep(1)	
    pi.set_servo_pulsewidth(24, 0)

#@webiopi.macro	
def cam_tilt_centre():
    pi.set_servo_pulsewidth(24, 1500)
    time.sleep(1)
    pi.set_servo_pulsewidth(24, 0)

#@webiopi.macro
def cam_stop():
    pi.set_servo_pulsewidth(23, 0)
    pi.set_servo_pulsewidth(24, 0)

#@webiopi.macro
def led_on():
	number = 1
	writeNumber(number)
	time.sleep(1)

#@webiopi.macro
def led_off():
	number = 0
	writeNumber(number)
	time.sleep(1)
	
# Start the webiopi server
server = webiopi.Server(port=8000, login="Hammerstein", password="Hammerstein")

# Register the macros

server.addMacro(cam_pan_left)
server.addMacro(cam_pan_right)
server.addMacro(cam_pan_centre)
server.addMacro(cam_tilt_up)
server.addMacro(cam_tilt_down)
server.addMacro(cam_tilt_centre)
server.addMacro(cam_stop)
server.addMacro(led_on)
server.addMacro(led_off)

# Run default loop
webiopi.runLoop()
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()

# Cleanly stop server
server.stop()

And here's the Arduino Nano code:

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);


The Nano code is only configured to switch on an LED connected to pin 13 of the Nano for now.
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Mon Aug 03, 2015 6:54 pm

I seemed to have found a workaround to my problem, probably very crude but I am a beginner.

I thought that I may be able to solve it by calling an external python script from within the main python script called by WebIOPi.

With a little Google work and trial and error I got it working.

I amended the led_on() Macro to call an OS command:

Code: Select all

#@webiopi.macro
def led_on():os.system("sudo python /home/pi/WebIOPi-0.7.1/my_projects/i2c_Serial_Test1.py")
Which calls this amended external python script:

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

def led_on():
	number = 1
	writeNumber(number)
	time.sleep(1)
	number = 0
	writeNumber(number)
	time.sleep(1)
	number = 1
	writeNumber(number)

led_on()
All this does is switch the LED on then off (not sure if its the second 1 or the 0 that turns it off??

Anyway if anyone knows a better way of running smbus from within WebIOPi please let me know.

Thanks
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Tue Aug 04, 2015 6:19 am

Thinking about this overnight, I need a better solution as my crude workaround involves calling a separate Python program every time I want to do anything, lots of opening, closing and unnecessary boverheads.
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Tue Aug 04, 2015 6:30 pm

Well it seems I solved my dilemma, all I needed to do was amend my RPi Python 3 installation to include smbus this now means smbus works fine, re-wired my robot and goys some wheels spinning.

I used the info on this page:
http://www.linuxcircle.com/2015/05/03/h ... -python-3/

Yippee.
Last edited by JonnyAlpha on Tue Aug 04, 2015 7:13 pm, edited 1 time in total.
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

asandford
Posts: 1998
Joined: Mon Dec 31, 2012 12:54 pm
Location: Waterlooville

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Tue Aug 04, 2015 7:06 pm

i2c isn't the best for RPi<==>Arduino comms, as the RPi can only be a master. In practise this means that you have to push and pull data to and from your device, and becomes cumbersome very quickly if you want to do more than flash an LED.
There are better supported protocols such as firmata and LLAP that run over serial to do this sort of thing (and over much longer distances than i2c can communicate over).
Have a look at Node Red as it supports the RPi GPIO and Arduino with firmata.

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Tue Aug 04, 2015 7:21 pm

asandford wrote:i2c isn't the best for RPi<==>Arduino comms, as the RPi can only be a master. In practise this means that you have to push and pull data to and from your device, and becomes cumbersome very quickly if you want to do more than flash an LED.
There are better supported protocols such as firmata and LLAP that run over serial to do this sort of thing (and over much longer distances than i2c can communicate over).
Have a look at Node Red as it supports the RPi GPIO and Arduino with firmata.
Mmmm this looks interesting, the reason I was pursuing i2c was to avoid using one of the two USB ports on my Pi B.
Looking through the documentation of Node Red it too can use i2c using the Jonny5 library?

I guess Node Red would replace WebIOPi?

The code looks very confusing :-)
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

asandford
Posts: 1998
Joined: Mon Dec 31, 2012 12:54 pm
Location: Waterlooville

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Tue Aug 04, 2015 8:32 pm

JonnyAlpha wrote: Mmmm this looks interesting, the reason I was pursuing i2c was to avoid using one of the two USB ports on my Pi B.
Looking through the documentation of Node Red it too can use i2c using the Jonny5 library?

I guess Node Red would replace WebIOPi?

The code looks very confusing :-)
If you run the nano at 3.3V (powered from the PI), then you can use the TX and RX pins instead (or use a level shifter if you have to power the nano at 5v).

NR can certainly replace Webiopi, and add loads more functionality (dashboards seem to be all the rage at the moment).

(With no disrespect intended) lighting an LED is crawling, using Johnny 5 is for when you can do a 4 minute mile :D (I've not used J5 with a Pi as node red has full support for the pi, but I have used it with an Intel galileo, and it isn't easy).

ultimately, what do you want to acheive as the Pi doesn't need a nano to flash LEDs or drive servos? (I only use nanos for timing critcal stuff like sending codes to remote controlled mains sockets and reading analogue values)

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Wed Aug 05, 2015 6:55 am

The reason for researching web interfaces is for building a web controlled robot, that I could drive around via a Web Cam.
Got the Motors and a servo working last night, I don't have any speed control yet though, motors just come on at full speed.
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

asandford
Posts: 1998
Joined: Mon Dec 31, 2012 12:54 pm
Location: Waterlooville

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Thu Aug 06, 2015 9:19 pm

JonnyAlpha wrote:The reason for researching web interfaces is for building a web controlled robot, that I could drive around via a Web Cam.
Got the Motors and a servo working last night, I don't have any speed control yet though, motors just come on at full speed.
NR is just javascript, about as webby as it gets.

I saw your other thread, and I still think you're making life hard for yourself, but education is the whole point of he PI.

Assuming you're using some sort of H-bridge controller for the motors (I hope you are!), using PWM will alter the speed: 0% - stop, 100% full speed, athother percentages don't really pan out as expected (I found with my ZumoBot that 25% gave me slow, 50% faster, 75% faster stll and 100% full speed).

If you are also planning on doing accurate turning angles then you'll also need some feedback from the wheels / motors.

This is bringing back memories of my A level electonics project which I combined with my A level computer science project to build a robot and write a 'Logo' interpreter on a BBC model B about 30 years ago!

User avatar
DougieLawson
Posts: 39297
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Thu Aug 06, 2015 9:53 pm

JonnyAlpha wrote: I guess Node Red would replace WebIOPi?

The code looks very confusing :-)
NodeRED couldn't make it any more confusing than WebIOPi (which I stared at for about an hour then decided I didn't like it).
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Thu Aug 06, 2015 10:32 pm

DougieLawson wrote:
JonnyAlpha wrote: I guess Node Red would replace WebIOPi?

The code looks very confusing :-)
NodeRED couldn't make it any more confusing than WebIOPi (which I stared at for about an hour then decided I didn't like it).
Dougie, what didn't you like, Node Red or WebIOPi?

I sort of know my way around WebIOPi, just need to sort out what's wrong with the PWM on the motors and Arduino and I'll have this cracked :-)
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

User avatar
DougieLawson
Posts: 39297
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Thu Aug 06, 2015 10:49 pm

I really do not like WebIOPi, I think it's exceedingly badly designed & documented and difficult to extend.

NodeRED is the new way of doing things with a graphical programming interface (which doesn't suit me either, because real programming is done in 72+8 columns of green assembler text on a black background), but at least NodeRED is sane and coherent and it's relatively easy to wire nodes together to build something useful.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

curiosity
Posts: 1
Joined: Sun Nov 08, 2015 3:24 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Sun Nov 08, 2015 3:41 pm

Sir, i have question, about smbus and webiopi, it is possible to import smbus and webiopi in one python script? Im very confused right now. I search the internet and said , smbus will conflict to webiopi,,

User avatar
JonnyAlpha
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 572
Joined: Sat Nov 02, 2013 2:06 pm

Re: i2c Serial Communication RPi and Arduino via WebIOPi

Mon Nov 09, 2015 8:35 am

If you look towards the top of this is what I did , I imported them both without error. The SMBUS did not work until I upgraded SMBUS for Python 3 following this info : http://www.linuxcircle.com/2015/05/03/h ... -python-3/

It's all working now.
Raspberry Pi Certified Educator. Main Hardware - Raspberry Pi 1 model B revision 2, Raspberry Pi 2 model B, Pi Camera

Return to “Interfacing (DSI, CSI, I2C, etc.)”