Thursday, April 4, 2013

Quick2Wire I2C Analog and Raspberry Pi

This is a review of the Quick2Wire Port Expander Combo kit and the Quick2Wire Analog Board. Both kits can be bought from a variety of sources, including CPC and SKPang in the UK.


The picture above shows the main interface board complete with ribbon cable for attaching it to a Raspberry Pi's GPIO header. On the right is the Analog board. The port expander board (included in the 'conbo' kit with the huge interface board, is a similar size and all the boards have 6 pin headers for I2C designed to be daisy-chained together using the cables supplied.

All three boards come as through-hole kits that are easy to assemble. Even easier if you rearrange the assembly instructions and solder the components in the order of those that lie lower to the boards first, rather than the apparently random order specified in the instructions.



The analog board is a nice size and has the pair of I2C connectors, a DIP switch to select the I2C address and various other quite useful headers. 
Mini Project
Its always good to see how these things work, so I decided to try out an analog input, using just a pot (variable resistor).


As you can see, a fair amount of desk space is required for this! The ribbon cables and sockets all have notches, so the only place that you beed to make sure you have the cable the right way around is on the Raspberry Pi.

The pot is wired to the analog board with one wiper to VREF, the other wiper to AGND and the slider (middle connection) to AIN0.

The AGND and VREF jumpers are both bridged and the DIP switches are in their original position.

Quick2Wire have their own Python library, but being familiar with I2C, I decided I didn't want to figure it out, and just used the standard stuff. This tutorial will get you set up using I2C.

Then, to make sure the device is working run:

$sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- 48 -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --            

This shows that the PCF8591 is on I2C address 48. If you have a revision 1 board use "-y 0" rather than "-y 1".

The following code is lifted unaltered from GrumpyMike (Mike Cook) here.

Just paste it into a file called "pot.py".

#Read a value from analogue input 0 
#in A/D in the PCF8591P @ address 0x48
from smbus import SMBus

bus = SMBus(1)

print("Read the A/D")
print("Ctrl C to stop")
bus.write_byte(0x48, 0) # set control register to read channel 0
last_reading =-1

while(0 == 0): # do forever
   reading = bus.read_byte(0x48) # read A/D
   if(abs(last_reading - reading) > 2):
      print(reading)
      last_reading = reading
Again, if you have an older revision 1 Pi, change  bus = SMBus(1) to be  bus = SMBus(0).

Run the program and you should see a new reading every time you move the pot knob.

$ sudo python pot.py
Read the A/D
Ctrl C to stop
150
147
144
141
138
135
132
129
126

Likes
DIP switches to select I2C address.
The daisy chain I2C idea, lets see some nice displays etc. in this format please.
I haven't mentioned that the expansion board also breaks out SPI and Serial connections from the Pi.


Dislikes
Their own library for all the I2C things. The 'standard' code works fine.
The interface is huge and largely devoid of any active components, it could easily be half the size.

Conclusion
This has the potential to grow into a really nice system, a bit like .Net Gadgeteer for Pi. But if you just want to have analog inputs on your Raspberry Pi then just stick a PCF8591 chip onto some breadboard and use jumper wires!



Friday, March 22, 2013

Leostick Review and Mini-Project

The Leostick is an Arduino Leonardo compatible board from Freetronics.

There are a number of things that make this board a great deal more than a clone:
  • Its smaller than the Uno / Loenardo sized Arduinos. In fact about the size of a USB flash drive.
  • It has a USB plug built onto the PCB, so you can plug it straight into the side of your computer to program it. Or use an USB extension lead.
  • It has a built-in RGB LED.
  • Being a Leonardo type board means that you can have it emulate a keyboard and mouse!
  • Flip it over and it has a piezo sounder on the back.

This all means that you can actually have quite a lot of fun with the Leostick straight out of its anti-static bag. However, the fun does not end there. Oh no, there is even more. The Leostick comes with a set of header pins and yes, they also sell little mini proto-shields that you can fit onto the Leostick.



Mini Project

To try out the Leostick, I decided to have a go at a little project from the second edition of my book '30 Arduino Projects for the Evil Genius' - out May 2013. This project was originally designed for an Arduino Leonardo.

It has two buttons, and when you press one it generates an obscure password and stores it in EEPROM. When you press the other button, it emulates a keyboard and types the password for you, wherever your password happens to be.

This proved to be really easy to do. Here is the finished result on a Leoshield.

Step 1.
Solder the header sockets onto the Leostick and the header pins onto the Leoshield.

It is easier to solder the header pins onto the shield if you first push them into the sockets on the Leostick.

Step 2. 
Solder the click switches and wires.


Make sure you get the switches the right way around. Look carefully at the diagram above. One way around there will be two unused holes between pins (left to right) the other way (vertically) there will be just one.

The bare wire at the bottom connects GND to one side of both switches. The other sides of the switches are connected to D7 and D6.

Here is the sketch, ignore the bit of paper that comes with the Leostick saying you need to download something, you don't, just use it like you would an Arduino Leonardo.



#include <EEPROM.h>

int greenPin = 9;
int soundPin = 11;
int typeButton = 7;
int generateButton = 6;
int passwordLength = 10;

char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

void setup()
{
  pinMode(greenPin, OUTPUT);
  pinMode(soundPin, OUTPUT);
  pinMode(typeButton, INPUT_PULLUP);
  pinMode(generateButton, INPUT_PULLUP);
  Keyboard.begin();
}

void loop()
{
  if (digitalRead(typeButton) == LOW)
  {
    notify(1);
    typePassword();
  }
  if (digitalRead(generateButton) == LOW)
  {
    notify(3);
    generatePassword();
  }
  delay(300);
}

void typePassword()
{
  for (int i = 0; i < passwordLength; i++)
  {
    Keyboard.write(EEPROM.read(i));
  }
  Keyboard.write('\n');
}

void generatePassword()
{
  randomSeed(millis() * analogRead(A0));
  for (int i = 0; i < passwordLength; i++)
  {
    EEPROM.write(i, randomLetter());
  }
}

char randomLetter()
{
 int n = strlen(letters);
 int i = random(n);
 return letters[i]; 
}

void notify(int n)
{
  for (int i = 0; i < n; i++)
  {
    tone(soundPin, 330);
    digitalWrite(greenPin, HIGH);
    delay(200);
    noTone(soundPin);
    digitalWrite(greenPin, LOW);
    delay(200);
  }
}


For good measure the sketch uses both the built-in RGB LED and the buzzer to provide feedback when you press a button.

To test it, just put your cursor in a blank document in an editor or wordprocessor. Pressing the button furthest away from the USB plug will generate a new password and beep three times, while flashing the LED green.

Pressing the other button will write out the password. So, now you can carry this everywhere with you and use it to type your passwords for you.

Summary

Pros

  • What's not to like - see everything I have written so far
  • Gold plated everything - Freetronics know how to make a good PCB
  • Pin usage labelled on the board and a jumper to break if you don't want sound.

Cons

  • A very minor, I2C SDA and SCL would be the icing on the cake. But probably not worth spoiling the pinout for.

Monday, February 18, 2013

Raspberry Pi and Breadboard (Raspberry Leaf)

I thought I would share this little helper I have made to simplify using the Pi with jumper wires.

If you are using your Raspberry Pi with Breadboard, and you have lots of connections to make, then the Pi Cobbler from Adafruit is pretty neat. However, sometimes you only need to make a couple of connections and the Cobbler is overkill and a few Male to Female jumper leads will do just fine.



The drawback with using Male to Female jumpers direct onto the GPIO is that you then have to count down the pins trying to find the pin you need, because nothing is labelled. Matching a diagram of the pinout to the actual pins is not easy and mistakes can be made.

Enter the Raspberry Leaf! Okay, so its just a bit of paper, with all the pin labels on. The image for this is at the end. Just save it, print it out, and cut around the border. It's saved at 300 dpi.

To fit it onto the GPIO pins, I found it easiest to make the holes first by placing it over some breadboard and pushing a header pin through each hole in turn.

Pushing it all the way down to the bottom of the GPIO connector needs tome help from a plastic tool - or if you turn off your Pi and, use a small screwdriver. DON'T DO THIS WITH THE Pi POWERED UP!!!

This has now become a permanent fixture on my prototyping Pi.

All the numbers refer to the BCM GPIO number, so if you are using the RPi.GPIO library then be sure to set the mode to BCM using the function setmode.

I hope you find it useful.

This is the template for the original R1 board saved at 300dpi - click it to open it in its own window. Also, here is a PDF version, that's hopefully easier to print the right size.

This is the template for the current R2 boards. PDF Version. Note that this was updated 20 Feb, 2013, as I had pins 2, 3 and 27 wrongly labelled!





Thursday, January 31, 2013

Minecraft, ComputerCraft and CreateSpace Self-Publishing

I have just finished a project with my son Matthew. We started it as something to do in the Christmas holidays. We decided to write a book on the Minecraft mod ComputerCraft. This extension to Minecraft allows you to do all sorts of really cool things with Computer Blocks within your Mincreaft world. These computer blocks can be programmed in the Lua language and can control things that move or lightup in the Minecraft world.


You can have computers, external monitors and you can even have wireless modems attached to your computers to build networks. There are also mobile computers, that you can also program, then send off to do your bidding, or even remote control from a panel of buttons (one of our projects).


We also made a project that uses the Twitter API to listen for Tweets for you and then carry out some action in your Minecraft world to signal the arrival of the Tweet that you can then go and read on your computer screen. Another project was a Morse code translator.



Having made some interesting projects, we wrapped it up into a book using the Amazon CreateSpace self-publishing platform. This was very easy to use, you even get an ISBN for free. The book is published as Print On Demand from Amazon, which means that when someone orders one it gets printed and a cover put on it. Even in full color, the price is pretty low.

We also made a separate version for Kindle - the files are automatically 'converted' for use on Kindle, from the same PDF that you upload to CreateSpace, but we found that the conversion did not really work and I reformatted it specifically for Kindle.

The book versions both go live almost instantly, despite dialogs warning you that it might take a week.

Anyway - if you are interested in the book, then you can buy it here. It is available as color (paperback) and Kindle, on most of Amazon's territories.






Monday, December 10, 2012

Raspberry Pi, Chronos Watch, Servos and a Laser

What a great combination! Raspberry Pi, Chronos watch, Servos and a Laser.

This is a real mash-up from two projects. One that displays accelerometer data from a Chronos watch, over its wireless link. The other project being the Adafruit tutorial on using their I2C servo controller.

I combined them to make a two-axis servo mounted laser that mirrors the movement of my arm wearing the watch.



Watch the video to see what it does.

WARNING: Don't shine lasers in your or anyone else's eyes. 



To get this working for yourself, then first follow this tutorial to get your Chronos watch talking to your Raspberry Pi. Nice code thanks to Sean Brewer.

Then build this Adafruit tutorial, but you will need two servos rather than one. Thanks to Kevin Townsend.

Once both are working independently, then build the servo assembly. I just super-glued one servo to the arm of another and glued the optional laser module to an arm for the top laser.



Laser modules vary in voltage requirements. This one is driven from 5V from the Raspberry Pi with a 100 Ω series resistor. Laser modules vary so check the data sheet.

Set your Chronos to ACC mode and dont forget to press [Down] so that it starts transmitting the data.

Here is the Python script that controls everything!


#!/usr/bin/python

from Adafruit_PWM_Servo_Driver import PWM
import time
import serial
import array


pwm = PWM(0x40, debug=True)

servoMin = 150  # Min pulse length out of 4096
servoMax = 600  # Max pulse length out of 4096
servoMid = (servoMax - servoMin) / 2 + servoMin

def startAccessPoint():
    return array.array('B', [0xFF, 0x07, 0x03]).tostring()

def accDataRequest():
    return array.array('B', [0xFF, 0x08, 0x07, 0x00, 0x00, 0x00, 0x00]).tostring()

def twos_comp(val, bits = 8):
  if ((val & (1 << (bits-1))) != 0):
    val = val -(1 << bits)
  return val

ser = serial.Serial('/dev/ttyACM0',115200,timeout=1)
ser.write(startAccessPoint())

pwm.setPWMFreq(60)                        # Set frequency to 60 Hz

while (True):
  ser.write(accDataRequest())
  accel = ser.read(7)
  x = twos_comp(ord(accel[0])) # -50 to +50
  y = twos_comp(ord(accel[1]))
  z = twos_comp(ord(accel[2]))
  #print(str(x))
  if x != 0 and y != 0 and z != 0 :
    pwm.setPWM(0, 0, servoMid-x*3)
    pwm.setPWM(1, 0, servoMid-y*3)
  time.sleep(0.1)







Friday, November 23, 2012

Using .NET Gadgeteer Modules with Arduino - Relay

The .NET Gadgeteer system has spawned a wide range of low cost and useful modules form places like GHI Electronics and Seedstudio.

I have a load of Gadgeteer modules, sitting in a cupboard, so I thought it would be good to see how hard it would be to use them with an Arduino. I decided to start with a nice easy one, this relay module from Seedstudio. It has four relays, each with an indicator LED.

The Gadgeteer modules are all connected by 10 way ribbon cable connectors. So clearly, the first thing we need is to make a lead that we can use to connect the module to breadboard.

I cut a lead in half and stripped the 10 wires from the half of the lead with the connector notch to the left. This turned out to be pretty easy. I was rather expecting it to go wrong and the leads end up all sorts of different lengths - but the wires stripped really easily.

I found that using a craft knife to separate the leads helped.
I then tinned the stripped wires and soldered them to a length of 10 pin header stuck into breadboard to stop it moving.

There we go, a lead that we can use with any Gadgeteer module.

The Gadgeteer system has many different types of pinout for these connectors. The relay module uses a type-Y socket, which is a general purpose IO arrangement. There are other types for serial, USB, I2C, analog and all sorts. They all use the same connectors, but have different pinouts.

You can find full details of all the pinout options here.

The pinouts for the type-Y are as below:



Here is a section of the Eagle schematic for the relay module (Open Source).

Although Gadgeteer modules are often 3.3V, this design will have no problem using 5V levels, so all looks promising. The control pins for the relays are connected to Gadgeteer pins 3, 4, 5 and 6.

The schematic shows the relay coils being supplied from 5V (pin 2), but testing with a multimeter, I found that the 'top' connection of the relay coil was actually connected to pin 1 (3.3V). I don't really understand this discrepancy, but no problem, in this case we can supply 5V from the Arduino to pin 1 of the module. That would be a bad thing to do for most types of Gadgeteer module - be Warned!

Here is the wired up breadboard:



  • Pin 1 of the Gadgeteer connector goes to Arduino 5V
  • Pin 10 of the Gadgeteer connector goes to Arduino GND
  • Pins 3, 4, 5 and 6 of the Gadgeteer connector goes to Arduino D2, D3, D4 and D5 respectively
Here is a little test sketch that lets you turn each Relay on and off using the Serial Monitor.




// Gadgeteer Relay Board

int relayPins[] = {2, 3, 4, 5};

void setup()
{
  for (int i = 0; i < 4; i++)
  {
    pinMode(relayPins[i], OUTPUT);
  }
  Serial.begin(9600);
  while (!Serial);
  Serial.println("A, B, C, D to turn relay on");
  Serial.println("a, b, c, d to turn relay off");
}

void loop()
{
  if (Serial.available())
  {
    char ch = Serial.read();
    if (ch >= 'A' && ch <= 'D')
    {
      digitalWrite(relayPins[ch - 'A'], HIGH);
    }
    if (ch >= 'a' && ch <= 'd')
    {
      digitalWrite(relayPins[ch - 'a'], LOW);
    } 
  }
}



Conclusion
Now that I have a lead, I need to think about which Gadgeteer module to try next!

Perhaps one of the I2C modules?

                                                                                         

Saturday, November 17, 2012

Review: Adafruit 16x2 OLED Display

If you are an Arduino user, you may well have used a 16x2 LCD display. These displays require a pot to set the contrast. The Adafruit 16x2 OLED display does away with the need for this pot. 

In all other ways it works just like an LCD 16x2 display and uses the standard LiquidCrystal library.

Its not that obvious from the photo above, but this display is lovely! The background is jet black under most lighting and the LED emissive display much clearer than the LCD equivalents.

It is not a cheap option, but for that special project, I Highly recommend this display.

Here's the code, straight from the Example sketch - with a few pin changes:

/*
  LiquidCrystal Library - Hello World
 
 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the 
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.
 
 This sketch prints "Hello World!" to the LCD
 and shows the time.
 
  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 
 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe
 
 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

void setup() {
  // set up the LCD's number of columns and rows: 
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis()/1000);
}