---

Thursday, October 4, 2012

Arduino Leonardo vs. Arduino Uno

I finally got chance to have a really good play with a Leonardo a few weeks ago. I was checking that the Arduino-based sections of 'Hacking Electronics' worked with the Leonardo as well as the 'standard' Uno.
  

The new book will contain about 25 sketches - well Arduino is just too useful not to include in the book. So, it was with some trepidation that I uploaded the first sketch. Some 24 sketches later, and I was a convert. In the end, everything worked, and with the application of a bit of common sense, sketches can be written to run unmodified on both boards.

Uploading.

The first thing that stumped me, was that, excited by the prospect of my Leonard being able to impersonate a keyboard, I uploaded a sketch, that would spew out some gibberish.


This worked fine of course. A very nice clean and simple class for pretending to be a keyboard - this is great, I thought. It wrote gibberish all over my sketch, but thats fine, I could unplug it and tidy it up. So, I decided to try out my next idea (a password entering gadget).



Press the button and it writes your password - pretty insecure really.

But the problem was, as soon as the Arduino IDE got focus, ready to press the Upload button for my new sketch, the old sketch started spewing nonsense all over it, and of course the upload couldn't be made to happen.

Oops I thought - and for one moment I wondered if I had bricked my Leonardo.

The answer of course, is to hold down the reset button (to shut it up) until the 'uploading sketch' message appears in the IDE then release it.

Phew, I was back in business.



Analog Inputs as Digital Outputs.

Most of the sketches I had trouble with were those where I was using analog pins A0 to A5 as digital outputs, by referring to them, using the old Arduino trick of adding 14 to their 'A number'. So, to use A0 as a digital output, you can just do:

pinMode(14, OUTPUT);

This did not work.

However, if you do:

pinMode(A0, OUTPUT);

It works just fine. What is more, it is actually clearer to see what is going on.

Note, that when referring to the analog inputs for their intended purpose, I did not put 'A' on the front of the pin numbers, I just did the following to read from A0.

int x = analogRead(0);



Shields.

The other area where I had a problem was in using a Leonardo with an old pre-R3 Ethernet shield. A bit of research indicated that an R3 Ethernet Shield should work just fine with it. I didn't have one to try.

The only other shield that I tried with it was the Freetronics LCD shield. This worked just fine.


Conclusion.

I really like the Leonardo, I love the USB keyboard and mouse emulation and the neat PCB layout. I also like that it is cheaper than an Uno, and has the following advantages:


  • More PWM pins
  • More digital pins full stop
  • Separate I2C pins (A4 and A5 are not dual purpose on Leonardo)
  • A second hardware serial port
So, what did I dislike?

Not much really - in theory, an advantage of the Uno is that if you destroy the ATmega328, you can replace it with a new one. But even with my usual lack of forethought, I think I have only had to do that once, and I spend a lot of time messing with Arduino.

The keyboard-gone-mad programming problem was understandable and really just my fault.

I suppose the only real down side that I see is if you have a lot of old shields that may have problems working. I also suspect there will be compatibility problems with some libraries.

Personally, I really like it, and will be using it again. If asked to recommend for someone just starting out with Arduino, I would love to be able to recommend a Leonardo, but I suspect sooner or later, they would run into a compatibility problem. So, I guess I would tell them to get one of each.

For a full list of the Leonardo's features go here.

Oh, and here is the password writing sketch. Obviously totally insecure - just a bit of fun.

char* password = "mysecretpassword\n";

const int buttonPin = 2; 

void setup() 
{
  pinMode(buttonPin, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() 
{
  if (! digitalRead(buttonPin))
  {
    Keyboard.print(password);
    delay(2000);
  }
}

About the Author
These are my books. Click on the image below to find out more about them.




                                                 

Sunday, August 26, 2012

Review of Raspberry Pi Prototyping Boards

We were all planning what we could do to hack some electronics with our Raspberry Pi's even before they arrived, and a little help in accessing and using those pins on the GPIO connector makes life a bit easier.

In this review, I look at the relative merits of three prototyping boards for the Rasspberry Pi. I use the term 'Prototyping' to distinguish them from expansion boards like the Gertboard and Pi Face that have buffers, level converters LEDs and other electronics attached to them. What I am talking about here is the Raspberry Pi equivalents to the Arduino ProtoShield. I.e. something that we can solder our own electronics to, in order to make something.

The products that I am reviewing are:
Oh the awful puns - thank you Raspberry Pi Foundation!

Prices are an indication only at the time of writing. Check the websites.

Be aware that all these products come as kits that must be soldered together. But then you are going to have more soldering to do anyway, to make your project, so no problem!

Lets look at each of these in a little detail:

Slice of Pi
I first used a Slice of Pi, that I bought on eBay, in the LED blinking project that I posted about here, and then later when trying out Ciseco's XRF wireless sensors with the Raspberry Pi here.



The first thing about the Slice of Pi is its cost. If you just have a little bit of electronics that you want to attach to your Pi, then there is enough space on the board to put in a DIL IC and a few extra components, which will probably do just fine for most projects.

The second thing that I like is the X-Bee format headers connected to the Pi's serial pins. This means that you can plug in all sorts of X-Bee format RF links. But, you don't have to, leave the sockets off for a bit more room on the prototyping area.

The connections are just simple socket headers, no fancy screw terminals, but again that is just fine in many cases, and sometimes you will not even need to fit them and just solder everything up on the board itself.

Humble Pi
At the time of writing (Aug 26, 2012) the Humbe Pi is only available for pre-order. Thanks to Ciseco for sending me one to play with.
The Humble Pi is the Slice of Pi's big brother. Again it fits over the Pi, this time covering almost the whole footprint of the raspberry Pi, with a cut-out around the RCA video connector.

Unlike the Slice of Pi, there are no header sockets. It is designed for you to built your whole project on the board. So, pretty much the whole of the board is taken up by a huge prototyping area.

The really nice touch is that the designer has placed pads in one corner for you to add your own 7805 compatible voltage regulator, 2.1mm DC power socket and associated capacitors. This means that you can potentially power the whole Raspberry Pi from a regular DC power supply of say 7 to 12V. Less with a LDO voltage regulator. 

Its a very useful board, that has been well thought out.

Pi Plate
The Pi Plate is the Rolls-Royce of Pi prototyping boards. 
It covers an even bigger area than the Humble Pi, by using an extra-tall header socket removing the need for a cut-out area. It is exactly the same size as the whole Raspberry Pi.

The board contacts are gold-plated and screw terminals are provided around the edge of the board that break-out the GPIO pins. If you prefer header sockets to screw terminals, then two connectors of 6 and 8 sockets are also catered for on the board. The first row of connections for the serial and I2C busses, the second for GPIO pins. Nice touch!

One corner of the board has a breakout area where a SOIC (surface mount chip) can be soldered. Something that has carried over from some Arduino Proto Shields and is very useful on occasion, for those chips that are just not available as through-hole.

There is no dedicated area for a voltage regulator. However, four of the screw terminals (top right) are not allocated to any Raspberry Pi GPIO connections, so it would be quite simple to use two for DC power-in and place the voltage regulator and capacitors on the general prototyping area.

As with all Adafruit products, the quality is high and the website contains good documentation.

Conclusion
There is no one board that you should always buy. It depends very much what you are trying to build. 

If it is a small project and the electronics will fit on a  Slice of Pi, use that.

If the project is too big for a slice of Pi and you are going to fit everything on the board and do not need screw terminals, then use the Humple Pi.

However, if the screw terminals would be useful, or you want a general purpose board to experiment with, then the Pi Plate is the best choice.

I fully expect to make good use of all three boards.

About the Author
These are my books. Click on the image below to find out more about them.






                           







Tuesday, August 7, 2012

LED Clock using Raspberry Pi

Okay, so if you were going to make a simple LED 4 digit clock, you probably wouldn't start with a Raspberry Pi.


But I wanted to test out I2C on the Pi and Adafruit's I2C LED displays looked like a good bet. I also used a level converter to convert the Pi's 3.3V I2C to the 5V I2C required by the LED module.

To recreate what I have done here you will need:
* Raspberry Pi
* Cobbler
* 4-digit 7 segment display and Backpack
* Level Converter
* Breadboard
* Jumper wires

Hardware
Connect up your Cobbler header as shown below. This is easier without the ribbon cable in place.
If you cannot make out the connections, they are:
* Cobbler GND to Level Shifter GND to Display GND
* Cobbler 5V to Level Shifter HV to Display VCC
* Cobbler 3.3V to Level Shifter LV
* Cobbler SDA0 to Level Shifter A1 (orange)
* Cobbler SCL0 to Level Shifter A2 (yellow)
* Level Shifter B1 to Display SDA (orange)
* Level Shifter B2 to Display SCL (yellow)

Software
I had to do the following to get I2C to work, following the instructions here:


sudo apt-get install python-smbus
sudo apt-get install i2c-tools (usefull but not essential)
sudo modprobe i2c-dev
sudo modprobe i2c-bcm2708

To simplify the process of using the display, I have created a Python library modelled on the Adafruit library for Arduino. You can download this from here and then cd into the extracted folder and do:

sudo python setup.py install


The clock program is included in the library as clock_example.py:


import i2c7segment as display
import time

disp = display.Adafruit7Segment()

while True:
    h = time.localtime().tm_hour
    m = time.localtime().tm_min
    disp.print_int(h * 100 + m)
    disp.draw_colon(True)
    disp.write_display()
    time.sleep(0.5)
    disp.draw_colon(False)
    disp.write_display()
    time.sleep(0.5)

For those looking for more information about the library, then just browse through the file i2c7segment.py, the methods are documented.

For more information about the display itself, including the segment mapping can be found at this useful thread.



About the Author
These are my books. Click on the image below to find out more about them.




                                                                                                                           


Sunday, August 5, 2012

Review: 4-digit 7-segment LED and RTC from Adafruit

In this review, I thought I would combine Adafruit's 0.56" 7-segment LED backpack and display and their DS1307 RTC (Real Time Clock) board. The obvious choice for such a combination is to make a simple clock!

Note that my pictures make the display look a little washed out. It wasn't, it was very bright. This is juts an effect of my photography lighting setup being even brighter.

Both modules are I2C and therefore just require two data pins along with GND and 5V. So, for anyone who has done their own multi-digit 7-segment LED multiplexing wiring up the breadboard becomes beautifully simple.

0.56" 7-Segment Backpack and Display

This comes as a kit of parts that need to be soldered together. Well actually just the PCB, header pins and the LED display itself. The surface mount chip is already soldered for you. 
Beginners will have no trouble with this, and Adafruit provide a very detailed construction guide.


DS1307 Real Time Clock breakout board kit

The RTC module is also supplied in kit form and would also suit someone new to soldering. Once again, the instructions are excellent. Showing you the right order in which to solder the components in a step-by-step manner with clear photographs as illustrations.


I got an extra resistor, but then I got more pin headers than I needed on both kits, so I think maybe its the Adafruit approach to err on the side of caution. Once assembled the Lithium battery (which should last years) can be inserted so that the module remembers the time.


Making a Digital Clock

Making the digital clock was delightfully simple, and basically merges together bits from the example scripts for the libraries for each module.

The Adafruit library for the display is nice, very easy to use. Their installation guide explains where to get it from github, along with a supporting library that it requires. 

The RTC module uses the Jee Lab's RTClib.

As normal with libraries, unzip the folders into your Arduino 'libraries' directory and then restart the Arduino IDE for it to pick them up. If you get an error message, as Arduino starts, about the libraries having invalid names, you missed the step of renaming the Adafruit libraries after unzipping them. Just rename the folders to remove the 'funny' characters and call them 'AdafruitLEDBackpack' and 'AdafruitGFXLibrary'.

Wire up your breadboard like this:



Coming from the Arduino, the leads are:
Red - 5V (Vcc)
Black - GND
Orange - A4 (SDA - data)
Yellow - A5 (SCL - clock)

These all just go to the pins with the same names on the two modules!

Paste the following sketch into a new Arduino window and upload it to your board. It will set the RTC to the time at which the sketch was compiled and uploaded. So, if your computer picks up its time from the Internet, that will be pretty accurate.
#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
#include "RTClib.h"

RTC_DS1307 RTC;
Adafruit_7segment disp = Adafruit_7segment();

void setup() 
{
  Wire.begin();
  RTC.begin();
  if (! RTC.isrunning()) 
  {
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  disp.begin(0x70);
}

void loop() 
{
  disp.print(getDecimalTime());
  disp.drawColon(true);
  disp.writeDisplay();
  delay(500);
  disp.drawColon(false);
  disp.writeDisplay();
  delay(500);
}

int getDecimalTime()
{
  DateTime now = RTC.now();
  int decimalTime = now.hour() * 100 + now.minute();
  return decimalTime;
}


Conclusion
These modules make life easy and free up Arduino pins for other uses. 

Great supporting documentation telling you all you need to know to get you started and more. Two very useful modules at not a bad price. 

Never again, will I be messing around multiplexing a load of LEDs with transistors for  the common anode and having the Arduino run off its feet refreshing! This is much easier!

[disclosure: These models were provided by Adafruit to me F.O.C]


About the Author
These are my books. Click on the image below to find out more about them.




                                                                                                                           

Thursday, July 26, 2012

Raspberry Pi GPIO driving Servo

I have experimented with GPIO on the Raspberry Pi, just turning an LED on and off here. But since then Ben Croston has improved the RPi GPIO Python library to do most of the work in C and I can confirm that it is a lot faster. Driving servo motors requires precise timing, so I decided to see how the Pi would perform this task.

Here is a video of the servo in action. It is set to stay on the left for a few seconds, then move to the middle position, then swing all the way to the right, then scoot back to the left.



As you can see it works, but is rather jittery. This would make it okay for some applications.

Here is what I did, for anyone wishing to try it for themselves.

Schematic


I did not like the idea of using the GPIO pin to directly drive the control signal for the servo. You may get away with it, but I wouldn't risk it, and it may not work as the GPIO pins are 3V where as the servo expects a 5V control signal.

The transistor I used was a BC548, but any similar NPN transistor (like the 2N2222) should do the trick.

Breadboard

To build this prototype, I used Adafruit's Cobbler. This very handy little gadget allows you to link the GPIO connector to breadboard.

Here is the breadboard layout:
You might want to open this up to full size to see what's going on.

The transistor is in the bottom three rows. The bottom most row being connected to GND on the cobbler, the base connection (second row up) is linked by a 1kΩ resistor to #17 on the cobbler.

An external 5V power supply was used to provide the power to the servo. I tried using the 5V connection from the servo, but even with big (2200µF) and small capacitors across the supply, the load from the servo was enough to crash the Pi. This external power supply was connected to the red and green jumper leads to the left.

A second 1kΩ resistor is connected from the external +5V to the collector of the transistor (third row up) using another 1kΩ resistor.

The connections to the servo are GND, +5V (from the external supply) and the control signal from the collector of the transistor (yellow lead).

Software

You will need to install the new version of the RPi.GPIO library from here. I used version 0.3.1a.

It requires you install python3-dev by entering the following from the terminal:

sudo apt-get install python3-dev

To install the library itself, fetch the archive from the link above, unpack into a directory and then run the command:

sudo python3 setup.py install

If you need more instructions on this, see my earlier post here. This part of the installation is the same, except I am now using python3 instead of python.

Here is the Python program to generate the pulses.


import RPi.GPIO as GPIO
import time

pin = 17
refresh_period = 0.02

GPIO.setmode(GPIO.BCM)

GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, True)

while True:
    for i in range(1, 100):
        GPIO.output(pin, False)
        time.sleep(0.001)
        GPIO.output(pin, True)
        time.sleep(refresh_period)

    for i in range(1, 100):
        GPIO.output(pin, False)
        time.sleep(0.0015)
        GPIO.output(pin, True)
        time.sleep(refresh_period)

    for i in range(1, 100):
        GPIO.output(pin, False)
        time.sleep(0.002)
        GPIO.output(pin, True)
        time.sleep(refresh_period)

This has to be run as root, so save it in a file called 'servo_test.py' and then run it with the command:

sudo python3 servo_test.py

The program generates pulses for the servo that look like this:


The pulses need to be about 20 mS apart, and the length of each pulse determines the servo position. A pulse of 1.5mS puts it in the middle position, 1.0mS one side and 2.0mS the other side.

Conclusion
The Pi can generate pulses fast enough to control a servo, but the operating system means that the pulses are not terribly reliable. The process may get interrupted at any time, lengthening the pulses, resulting in the jitter that you see.

If you want true accurate control, then you probably need to have the Pi delegate looking after the servos to an Arduino, as I do in my Pi with Arduino over USB blog post.


About the Author
These are my books. Click on the image below to find out more about them.





                                                                                                                           

Tuesday, July 3, 2012

Raspberry Pi meets Arduino - part 2

I gave a short talk and demonstration yesterday evening at the #raspberryjam event in Preston. I demonstrated the Pi raising some servo driven flags attached to an Arduino. I would have demonstrated communication in the other direction using a ultrasonic rangefinder, but I ran out of time. That can be my next post.

Here is the code and details of the electronics for all this.

Flags



First of all the electronics. Here is a wiring diagram for the servos. 


The servo control pins are wired to D2 and D3.

The Arduino is powered by a separate power supply into its DC power socket. I used a 9V 1.5A power supply. The USB lead is connected from the Arduino to the Pi. I was running tightVNC on the Pi, so I could remote control it from my Mac without having to attache keyboard mouse and TV.

Arduino

Here is the Arduino sketch.
#include <Servo.h>

#define MIN_ANGLE 30
#define MAX_ANGLE 160

#define SERVO_1_PIN 3
#define SERVO_2_PIN 2

Servo servo1;
Servo servo2;
int servo1pos = MIN_ANGLE;
int servo2pos = MIN_ANGLE;

void setup()
{
  servo1.attach(SERVO_1_PIN);
  servo2.attach(SERVO_2_PIN);
  Serial.begin(9600);
}

void loop()
{
  if (Serial.available())
  {
    char ch = Serial.read();
    if (ch == 'a')  servo1pos = MAX_ANGLE;
    else if (ch == 'A')  servo1pos = MIN_ANGLE;
    else if (ch == 'b')  servo2pos = MAX_ANGLE;
    else if (ch == 'B')  servo2pos = MIN_ANGLE;

  }
  servo1.write(servo1pos);
  servo2.write(servo2pos);
  delay(20);
}

All nice standard stuff. It listens on the serial connection for one of the single character commands 'a', 'A', 'b' or 'B' and when it gets one it raises or lowers the appropriate flag.

Python

The Python script from the Raspberry Pi end is equally simple. However you will need to install the pyserial library.

Step 1. If you are not reading this page on your Pi, then switch now, so you can copy and paste.

Step 2. Browse to here and download pyserial-2.5.tar.gz (106.3 kB) and save it somewhere convenient like the Desktop.

Step 3. This is a gziped tar file. Which needs unzipping and untaring. To unzip it open a Terminal, which you will find from the 'start menu' under 'accessories'. Now paste the following commands into it.
cd /home/pi/Desktop/other
gunzip pyserial-2.5.tar.gz
tar - xvf pyserial-2.5.tar

Step 4. Install pySerial, by typing these lines in your terminal window:
cd pyserial-2.5
sudo python setup.py install



Startup IDLE (use Python 2 NOT 3) and open a new file, pasting the following code into it:


from Tkinter import *
import serial
import time

DEVICE = '/dev/ttyACM0'
BAUD = 9600
ser = serial.Serial(DEVICE, BAUD)

root = Tk()

def aUp() :
    ser.write('a')
    return

def aDown() :
    ser.write('A')
    return

def bUp() :
    ser.write('b')
    return

def bDown() :
    ser.write('B')
    return

Button(text='A up', command=aUp).pack()
Button(text='A down', command=aDown).pack()
Button(text='B up', command=bUp).pack()
Button(text='B down', command=bDown).pack()


root.mainloop()


Then run the script and the four buttons should appear.

Here is a short video showing the flags in action.






About the Author
These are my books. Click on the image below to find out more about them.




                                                                                                                           

             


Tuesday, June 12, 2012

Raspberry Pi and Wireless Sensor

A few weeks ago, I blogged about at a 'shield' that plugs into the Raspberry Pi's GPIO port called the 'Slice of Pi'. This very low cost board also includes an X-Bee shaped socket into which RF modules can be plugged. The company behind the 'Slice of Pi' (Ciseco) is also behind a useful and low-cost range of RF devices.

In this blog entry, I used one of their wireless sensor modules (in this case temperature) with a pair of XRF RF modems to add remote wireless temperature sensing to the Raspberry Pi using the serial connection on the GPIO pins.


Here, a simple program (on the left) reads the temperature from the remote wireless sensor and displays it (in the right). Degrees C not F, its not that cold over here!

Hardware

Here is the Raspberry Pi, with a Slice of Pi and an XRF module all plugged together sandwich style.


I plugged them together with the Pi turned off, as 'hot-swapping' makes me nervous.

The wireless temperature sensor is made up of two modules, the temperature sensor module, complete with Lithium battery, and another XRF module -- the same as the one attached to the Pi. These just plug together.


Software

The temperature module sends the temperature as a string every 15 seconds. So all that is required of the Raspberry Pi is to catch the serial messages and display them in a Tkinter window. The sensor is microcontroller-based and quite smart, so you can do much more complicated things, including multiple sensors, sensor IDs and messages that indicate that the buttons on the sensor have been pressed.

The Python program to do this is listed in full below (20 lines of code). It requires the PySerial library which you must install. See the instructions in my earlier post  on linking the Pi to an Arduino.

From IDLE (use Python 2 not 3) select File->New and paste in the code below, then click 'Run Module'.


from Tkinter import *
import serial
import time

DEVICE = '/dev/ttyAMA0'
BAUD = 9600

root = Tk()

def updateTime() :
    ser = serial.Serial(DEVICE, BAUD)
    n = ser.inWaiting()
    if n == 4 :
        msg = ser.read(n)
        v.set(msg)
    ser.close()
    root.after(2000, updateTime)

v = StringVar()
Label(root, textvariable=v, font=("Helvetica", 240)).pack()
v.set('--.-')

root.after(2000, updateTime)
root.mainloop()



Conclusion
These are great modules with long range and low power consumption. For the full specs, visit Ciseco's website.

Thanks
Thanks to Ciseco for lending me the hardware - I will send it back, I promise!


                                                                                                                           


About the Author
These are my books. Click on the image below to find out more about them.