Categories
Arduino Creative Family Gadgets Geekery Raspberry Pi

Indiana Jones Idol Swap party game

My sister in law does epic children’s parties (a couple of years back I had a lot of fun playing Snape and being mean to all the kids who weren’t in Slytherin) and this year I was given a request to build a game for an upcoming Indiana-Jones themed party.

Remember that bit at the very beginning of Raiders of the Lost Ark where Indy has to balance the idol with a bag of sand to avoid the traps going off?

“Can you build a game that does that?”

So I started thinking along the lines of using an Arduino coupled with a weight sensor which triggers an attached Raspberry Pi to play a tune when the idol is balanced, all packaged up inside a suitably rock looking biscuit tin:

I've got a bad feeling about this
I’ve got a bad feeling about this

The idea would be the idol would be swapped, the Arduino would detect the swap, determine if the weight was different and then set off an alarm and rumble motor if it was. If it was the same weight it would play the Indiana Jones music.

The Arduino has lots of analogue pins that can read changes in voltage, and the Pi can take care of the music and sound effects – it would also be possible to  hook it up to a TV to play the appropriate bit of the film, as chasing down seven year olds with a giant boulder / dart traps / snake pits might not go down well with their parents.

Initially I looked at using a load cell sensor similar to what’s found in electronic scales, however I discovered that the resistance generated by these sensors to be really tiny, and it’s not just a simple matter of hooking them up to an Arduino. Note – since I built my initial version Sparkfun have actually brought out a handy load-cell amplifier kit that should make this possible for version 2!

So instead I opted for a much simpler force sensor – these are widely available and their resistance can be easily measured, but they’re also a bit inaccurate. For the purposes of the game and to add a bit of random variability I decided to go with this simpler route.

My arduino circuit is as follows – it includes an LED to indicate if the pressure sensor is detecting the idol properly. The Arduino communicates with the Pi over serial to then trigger the appropriate sound file. I ran out of time to include the rumble motor but it would be quite easy to add one.

Adafruit have a tutorial along with some suitable code which can be used to send the force sensor output to the Raspberry Pi  via serial:

/* FSR testing sketch. 
 
Connect one end of FSR to 5V, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground
Connect LED from pin 11 through a resistor to ground 
 
For more information see www.ladyada.net/learn/sensors/fsr.html */
 
int fsrAnalogPin = 0; // FSR is connected to analog 0
int LEDpin = 11;      // connect Red LED to pin 11 (PWM pin)
int fsrReading;      // the analog reading from the FSR resistor divider
int LEDbrightness;
 
void setup(void) {
  Serial.begin(9600);   // We'll send debugging information via the Serial monitor
  pinMode(LEDpin, OUTPUT);
}
 
void loop(void) {
  fsrReading = analogRead(fsrAnalogPin);
  Serial.print("Analog reading = ");
  Serial.println(fsrReading);
 
  // we'll need to change the range from the analog reading (0-1023) down to the range
  // used by analogWrite (0-255) with map!
  LEDbrightness = map(fsrReading, 0, 1023, 0, 255);
  // LED gets brighter the harder you press
  analogWrite(LEDpin, LEDbrightness);
 
  delay(100);
}

This also lights up an LED to give useful visual feedback – the Pi then just listens on the serial input and triggers the according sound effect.

Assembled the sensor looks like this (the force sensor is under the lid of the coffee tin):

Indiana Jones style trap game
Indy was out so Han stepped in

Inside my ‘Idol’ (which was a papercraft model printed on shiny paper), was a counterweight made from a stack of pennies – this is reasonably heavy and I was able to adjust the sensitivity of the circuit to detect the presence (and absence) of the Idol.

To build the pedestal I used an octagonal quality street plastic box, covered in paper mache and spray-painted with stone effect spray paint. The arduino and pressure sensor were contained inside a metal coffee tin.

On detecting the Idol being removed, the Pi plays the sound sample “It belongs in a museum” from Raiders of the Lost Ark, if the sensor is successfully fooled it plays the Indiana Jones theme!

After a bit of play testing we found that balancing the idol was very hit and miss – although a handy rock nearby seemed to do the job most of the time. Ideally this would use the much more accurate load cell to measure the weight of the idol and compare it to the bag of sand after a button press. I still have all the parts, so I’m just waiting for the next time someone in my family holds an Indiana Jones themed birthday party.

Indiana Jones Idol Swap game
Here it is (running off a USB battery)
Categories
Arduino Creative Geekery

Countdown to Christmas with the Arduino advent calendar!

This year, as part of the publicity for their Christmas charity gifts, Concern Worldwide (who I’m lucky enough to work for) commissioned an artist to come up with a design for an advent calendar.

The resulting design by Robert Fiszer is really rather lovely (you can check out the campaign here)- and lends itself rather well to be illuminated as a Christmas decoration for the Concern office.

Concern Advent Calendar designed by Robert Fiszer
Concern Advent Calendar designed by Robert Fiszer

So as a spare tinkering time project I thought I would have a go at building an Arduino controlled LED advent calendar that illuminates the relevant day and counts down to the 24th.

My requirements needed it to be powered by USB, and that it’s a standalone project with it’s own date clock – as the office IT department would frown upon me installing things on my work PC to run Christmas decorations from. In order to do this I needed to read up on using a battery backed up RTC (Real Time Clock) and a way to control 24 LEDs from my arduino micro.

I decided on using a shift register – the other option would be to use a chain of NeoPixel LEDs, but I wanted to learn about shift registers and get an idea about how they worked. For an excellent introduction to shift registers check out this blog from Bildr.

Essentially a shift register is a way of converting a serial signal from the arduino into a parallel series of high and low signals to the output pins on each chip. Each shift register has 16 pins, 8 output pins, 2 earth pins, 2 positive 5 volt pins, 3 serial input pins consisting of clock, latch and time signals, and a final serial output pin which is used when daisy chaining them together.

The 74HC595 8-bit Shift Register I used was available cheaply on ebay and looks like this:

My diagram of a shift register
There are better diagrams out there but this helped me

Wired up with an arduino on breadboard it looks like this:

Teaching myself about shift registers and Larson scanners #arduino #kitt #cylon

A video posted by Pete Taylor (@kimondouk) on

Even with just 8 outputs it looks a bit messy. With 3 shift registers daisy chained together it looks even more complicated:

Now with 3 shift registers and 24leds #arduino #adventcalendar

A video posted by Pete Taylor (@kimondouk) on

But remember the diagram above – the circuit is still fairly simple, what makes it look complicated is the loops of wire which are all the same length. The challenge I found with the chip is that one of the outputs is on one side, with the remaining 7 on the other.

To tidy everything up, I soldered the chips in carriers onto a piece of full sized Adafruit perma-proto breadboard. I highly recommend using this stuff – it costs a bit more than the generic soldering boards you can buy on ebay, but it’s strong and laid out sensibly using the same layout as standard prototyping boards. In my layout I spaced the shift registers 1 hole apart and moved the offside output around the corner of the chip, so that all 8 outputs were on the same side. To connect my LEDs I was able to add 8 socket female headers as I found soldering the LED wires directly into the board was difficult as the stranded copper wire would snap easily. Plus using headers gives me the option to swap out the LEDs for something else in the future. For LEDs I found pre-soldered 5 volt LEDs available on ebay that included the resistor.

My board includes 4 shift registers giving me a total of 32 outputs – this would enable me to re-purpose the board in future, as I’m thinking after advent it would make a nice monthly calendar.

Here’s the board without any of the LEDs attached:

Shift register without the LEDs
Shift register without the LEDs

For the time circuit I used a DS 1307 RTC – the one I used shares the same chipset as the Adafruit one detailed here (link) (normally I’d buy the adafruit one to support their website, but I couldn’t find it available online).

The code:

/*
Shift register calendar
*/

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)  // for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
   #define Serial SerialUSB
#endif

RTC_DS1307 rtc;

// shift register setup

//**************************************************************//
//  Name    : shiftOutCode, Dual One By One                           //
//  Author  : Carlyn Maw, Tom Igoe                               //
//  Date    : 25 Oct, 2006                                       //
//  Version : 1.0                                                //
//  Notes   : Code for using a 74HC595 Shift Register            //
//          : to count from 0 to 255                             //
//**************************************************************//


int SER_Pin = 4;   //pin 14 on the 75HC595
int RCLK_Pin = 5;  //pin 12 on the 75HC595
int SRCLK_Pin = 6; //pin 11 on the 75HC595

int caldate = 0;

//How many of the shift registers - change this
#define number_of_74hc595s 4

//do not touch
#define numOfRegisterPins number_of_74hc595s * 8

boolean registers[numOfRegisterPins];

void setup() 
{
  pinMode(SER_Pin, OUTPUT);
  pinMode(RCLK_Pin, OUTPUT);
  pinMode(SRCLK_Pin, OUTPUT);


  //reset all register pins
  clearRegisters();
  writeRegisters();

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
   rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 6, 2014 at 3am you would call:
    //   rtc.adjust(DateTime(2014, 1, 6, 3, 0, 0));
  }
}

//set all register pins to LOW
void clearRegisters(){
  for(int i = numOfRegisterPins - 1; i >=  0; i--){
     registers[i] = LOW;
  }
  writeRegisters();
} 


//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)

void writeRegisters(){

  digitalWrite(RCLK_Pin, LOW);

  for(int i = numOfRegisterPins - 1; i >=  0; i--){
    digitalWrite(SRCLK_Pin, LOW);

    int val = registers[i];

    digitalWrite(SER_Pin, val);
    digitalWrite(SRCLK_Pin, HIGH);

  }
  digitalWrite(RCLK_Pin, HIGH);

}

//set an individual pin HIGH or LOW
void setRegisterPin(int index, int value){
  registers[index] = value;
}


void loop() 
{
  DateTime now = rtc.now();
  caldate = now.day();
  Serial.print(caldate);
   Serial.print(now.day(), DEC);
 
  delay(1500);
  clearRegisters();
  delay(500);

  for (int i = 0; i < caldate; i++)
  {
   setRegisterPin(i, HIGH);
   writeRegisters();
  delay(100);
  }
}

Note – the RTC was the trickiest part of the circuit, and after reading lots of posts from people who’ve had issues with the DS1307 I’d recommend using one of the integrated chip varieties.

The code for the calendar is fairly simple – it checks the date from the RTC and then lights up the appropriate number of lights. I’ve made it loop to give a bit more visual interest, but it’s easy enough to modify the code to make it just light up once when you plug it in.

Assembly

I printed out the calendar image and pasted it onto a bit of board with holes behind each ‘light’. Using a frame from a previous project (the Concern general election Swingometer) to bring it all together. To mount the LEDs I used bottle tops – this involved drinking a lot of diet coke, and when I ran out of that, wine.

Back of the advent calendar
Back of the advent calendar

Here’s the final version, in action as if it’s Christmas Eve showing all the lights as I removed the RTC.

The #arduino shift register powered #adventcalendar is now finished! Happy #1stdecember

A video posted by Pete Taylor (@kimondouk) on

If you liked this project, please buy a gift from Concern’s shop – my personal favourite is the solar lights as they are a neat technological solution to the tricky problem of lighting.

Categories
Arduino Gadgets

The smallest USB mechanical keyboard in the world*

Sometimes it’s annoying when your favourite old school mechanical keyboard lacks some of the modern function keys that we’ve grown used to using in recent years. Or you might be re-purposing a keyboard for a use it wasn’t really designed for – I have a lovely chicklet keyboard with my Raspberry Pi Motorola Lapdock hack which lacks both left and right windows keys.

You can of course usually find a way round these limitations by hitting control and frantically hammering in the number of the function key (if you can remember it) – but sometimes that doesn’t work. For example the ArcEm emulator that runs on the Raspberry Pi RISC OS requires both left and right windows keys to be pressed simultaneously to exit.

Fortunately to the rescue is this – the smallest USB mechanical keyboard in the world (probably):

Smallest USB keyboard in the world
Now I just need a portal gun

The blue Cherry MX keys are illuminated, and for 10 seconds when you first plug it in you can remap them to almost anything (including words and short phrases). I did find a couple of programmable USB keystrips that offered similar functionality, but these were a bit expensive and lacked mechanical keys. If you shop around for the parts you can build this for less than £15.

Build guide:

First you need a few parts:

  • An Adafruit USB trinket (5v) In the UK available from Pimoroni
  • 2 x MX cherry keys (try ebay – e.g. this listing)
  • 2 x keycaps (lots on Amazon)
  • 2 x 3mm LEDs (and a 50 ohm resistor)
  • A mini (the older not micro) USB cable
  • Some wire
  • A suitable box (the one I used was a little on the small size – something 6cm x 3cm x 3cm might be better)
  • Craft knife, dremel, soldering iron, multimeter with continuity tester

This project does require a bit of soldering – I opted to solder the pins onto the the trinket, and then attach the wires using female jumper cables – for a neater build you could solder the wires directly between the cherry keys and Trinket. If you’re opting for total neatness you can also solder the USB wires directly to the underside of the Trinket as there are some surface mount tabs.

A costlier but wireless alternative to the Trinket is the Adafruit Bluefruit EZ HID keyboard controller again available from Pimoroni in the UK.

Putting it together

This is based on the Adafruit USB Trinket – a very cut down minimalist Arduino clone (it runs some simple Arduino code no problem, but needs it’s own version of the programmer tool). Adafruit have a tutorial which shows how to wire up a Trinket to act as a USB HID along with a couple of code examples.

First step is to try out the Adafruit tutorial on some breadboard – if you get stuck head over to the forums where Frank can help – to get this to work on my Mac I needed to plug the USB cable into a USB 2 port directly (not via a hub) and use the experimental library. Make sure you’re using Adafruit’s version of the Adruino IDE – all the info is on the Trinket page.

Adafruit Trinket as a USB keyboard
Trinket as a USB keyboard

Plug this in and try out uploading the sketch – when you first connect the Trinket the red LED will blink for 10 seconds – you have to hit the upload button on the Arduino IDE app in this time for it to work. Once the red LED has stopped blinking, your computer should recognise the keyboard.

We’re using exactly the same circuit, with the exception of adding 2 LEDs in series. The trinket has a 5v pin which supplies just about the right amount of power for the LEDs I used but check with an LED circuit calculator to see if you need to add a resistor. The Cherry switches have 2 small holes for the LED wires to sit in.

Next we need to prepare the keys and a box for them to sit in – here for some Dremel action!

Photo of USB keyboard before assembly
all the bits, prior to wiring

The Cherry keys are wedge shaped so cut a hole slightly too small and then widen using the Dremel – they are about 12mm square. I did find this a little messy and resorted to using a glue gun to tidy things up! for a neater build you could try a hot knife cutter, or for the über neat build 3d print a proper case. Fortunately once the keys are in place you don’t really see the holes.

Once the keys are fitted, solder on some wires. Note that the pins from the cherry keys are quite brittle (they’re designed to sit in a printed circuit board) so avoid bending them if possible.

The wiring arrangement I used was this:

Cherry keyboard wiring
Cherry keys viewed from the underside

Make sure the LEDs are wired in series (+ to – to + to -) – you can identify the positive (anode) lead on the LED as it’s the longer one. The LED and key circuit can all share the same ground connector. It doesn’t matter which way round you add the resistor.

Once you’ve got everything soldered together, plug it in and test – especially before putting the box together. I found cramming it all into the case a bit tricky but managed it just. I cut up a USB mini cable and re-soldered the wires to fit in the box. As I mentioned previously – soldering the wires directly to the Trinket would save a lot of space.

USB keyboard internal wiring
here it is, tight fit.

Finally enjoy your mechanical keyboard! – although this has only 2 keys, the action on the Cherry MX blues is so nice I’m now thinking I might need to invest in a proper full size one.

*probably – I’m not expecting a call from Guinness just yet.

Update – I’ve potentially been outdone with the single key keyboard which has been launched on Kickstarter.

Categories
Arduino Gadgets Geekery Raspberry Pi

Raspberry Pi + Arduino + 8×8 LED Matrix + Python = Raspberry Pi LED display

The other week at work we launched a petition to support lifesaving Aid using a Jumbotron display, so I’ve been inspired to have a go at building a (very) mini version using my Raspberry Pi and an Arduino.

This is a handy way of getting your Pi to display information from any Python app you may have written – so you could use it to make a new email notifier, flash up messages from twitter, or if you’re using your Pi as a server without a monitor – status update messages. I’m interested in using it as a ‘now playing’ message board for an email controlled spotify jukebox I’m working on (more updates to follow).

There are lots of ways you could achieve this – it’s certainly possible to drive LED displays directly from the Raspberry Pi GPIO pins, but this is method is easy to do as it uses off the shelf kits, provides a bit of soldering practice, and an opportunity to learn a bit about Arduinos, Python and serial communications. As with a lot of Arduino projects once you’ve got the hand of how things work you could easily build a cheaper version using only the parts you need. Plus these are my first steps getting an Arduino to do something more interesting than flash a single LED on and off.

I’ve been using a standard Arduino Uno which is available for around £20, and the LED Matrix Shield v.1 from Ciseco which is £5 – this is a Arduino add on board that sits on top of the Arduino. The Matrix shield is fun to put together and good for practising soldering, as a lot of the parts aren’t particularly heat sensitive.

Setting up the Arduino

The instructions that come with the Matix shield are a bit basic – for a much better step by step how to check out this tutorial which I found in the forums.

LED matrix shield Ciseco
LED matrix shield sat on top of an Arduino Duo

Next step is to prepare the Arduino with the code you need it to run. Unlike the Nerdkit microcontroller I mentioned in a previous post the Arduino has a nice user friendly graphical front end – the downside to this is that it runs quite slowly on the Raspberry Pi. I used my Mac to upload the code to the Arduino – just remember to connect it directly to the USB ports on your Mac and not via a USB hub.

First you’ll need to add frequencytimer.h to your Arduino Library – there are instructions on how to install libraries here and you can download frequency timer here.

Then you’ll need to download 8x8LEDMatrix written by Andy Lindsay who has all sorts of other interesting Arduino / Pi stuff on his blog.

The script includes a 5×7 font file which you can experiment with to get the display to show different characters. Compile and upload this to your Arduino to check that everything’s working properly.

Now you’ll need to modify Andy’s code to send the text you want your Arduino to display over the serial port. Using a tilda character clears the script (although I discovered you don’t actually need this as the Pi resets the Arduino when it communicates with it on the serial port)

/*
 * Show messages on an 8x8 led matrix,
 * scrolling from right to left.
 *
 * Uses FrequencyTimer2 library to
 * constantly run an interrupt routine
 * at a specified frequency. This
 * refreshes the display without the
 * main loop having to do anything.
 *
 */

#include
#include &amp;amp;quot;font5x7.h&amp;amp;quot;

#define DELAY 80

int incomingByte = 0;   // for incoming serial data
String incomingString; // for the incomming serial data string
char message[] = &amp;amp;quot;&amp;amp;quot;; // define the message

byte col = 0;
byte leds[8][8];

// pin[xx] on led matrix connected to nn on Arduino (-1 is dummy to make array start at pos 1)
int pins[17]= {
  -1, 17, 8, 7, 19, 9, 13, 4, 10, 6, 5, 18, 3, 2, 11, 12, 16};

// col[xx] of leds = pin yy on led matrix
int cols[8] = {
  pins[13], pins[3], pins[4], pins[10], pins[06], pins[11], pins[15], pins[16]};

int rows[8] = {
  pins[9], pins[14], pins[8], pins[12], pins[1], pins[7], pins[2], pins[5]};


void setup() {

  // sets the pins as output
  for (int i = 1; i  0) {

                // read the incoming byte:
                char incomingByte = (char)Serial.read();

                incomingString += incomingByte;

                if (incomingByte == &amp;amp;#039;~&amp;amp;#039;) {
                  // using a tilda ~ clears the string

                incomingString = &amp;amp;quot;&amp;amp;quot;;

                }

                // check string for command variables

                incomingString.toCharArray(message, 160);



                }





  scrollMsg( message );




}

void clearLeds() {
  // Clear display array
  for (int i = 0; i < 8; i++) {
    for (int j = 0; j < 8; j++) {
      leds[i][j] = 0;
    }
  }
}

void setChar(char ch) {

  for (int i = 0; i < 5; i++) {
    unsigned char bt = pgm_read_byte(&amp;amp;amp;(smallFont [(ch-32)*5 + i] ));
    for (int j = 0; j < 8; j++) {
      leds[j][i+1] = (bt &amp;amp;amp; 0x01);
      bt = bt >> 1;
    }
  }
}

void slideChar(char ch, int del) {
  for (int l = 0; l < 5; l++) {
    for (int i = 0; i < 7; i++) {
      for (int j = 0; j < 8; j++) {
        leds[j][i] = leds[j][i+1];
      }
    }
    unsigned char bt = pgm_read_byte(&amp;amp;amp;(smallFont [(ch-32)*5 + l] ));
    for (int j = 0; j < 8; j++) {
      leds[j][7] = (bt &amp;amp;amp; 0x01);
      bt = bt >> 1;
    }
    delay(del);
  }

  for (int i = 0; i < 7; i++) {
    for (int j = 0; j < 8; j++) {
      leds[j][i] = leds[j][i+1];
    }
  }

  for (int j = 0; j < 8; j++) {
    leds[j][7] = 0;
  }
  delay(del);
}


// Interrupt routine
void display() {
  digitalWrite(cols[col], LOW);  // Turn whole previous column off
  col++;
  if (col == 8) {
    col = 0;
  }
  for (int row = 0; row < 8; row++) {
    //    if (leds[col][7 - row] == 1) {
    if (leds[col][ row] == 1) {
      digitalWrite(rows[row], LOW);  // Turn on this led
    }
    else {
      digitalWrite(rows[row], HIGH); // Turn off this led
    }
  }
  digitalWrite(cols[col], HIGH); // Turn whole column on at once (for equal lighting times)
}

Once you’ve uploaded this you can test its working properly by clicking on the serial monitor icon (the magnifier glass on the right hand side) and typing some text – if everything is working OK you’ll see the text appear on your Arduino’s matrix display.

Arduino software
Click on the magnifier icon on the right hand side

Setting up the Raspberry Pi

Now you need to connect the Arduino to the Pi. I’ve used one of the Pi’s USB ports rather than via a USB hub – you could also use the serial pin on the GPIO port to do this as well. Make sure the Arduino is connected before you power up the Raspberry Pi.

You can test the Pi -> Arduino control with minicom (thankyou http://codeandlife.com/2012/07/29/arduino-and-raspberry-pi-serial-communication/

Install minicom on the pi via the console:

sudo apt-get install minicom

then run minicom and connect it to the Arduino:

minicom -b 9600 -o -D /dev/ttyAMA0

Hopefully everything you type into the console will be appearing on the Arduino Matrix.

Next is to get Python to send data to the Arduino over the serial port. Install the python serial libraries:

sudo apt-get install python-serial

Now you’re ready to write some Python code to control the Arduino’s LED display. I’ve been using the IDLE app on the Raspberry Pi. The following code is a super simple python script that can send some text to the LED Matrix:

import time
import serial

#configure the serial connection

ser = serial.Serial("/dev/ttyACM0",9600)

ser.open()

# add some time delays to stop the Arduino resetting

time.sleep(1.5)

ser.isOpen()

time.sleetp(1.5)

ser.write("Raspberry Pi")

Hit f5 and you should see this:

Arduino LED MAtrix Shield v1.0 IOT Research 2012
Bingo! or whatever you want it to say…

And that’s it – you now have a neat way of controlling an LED display with Python. The LED display always shows the last message it received until it gets a new one.

Update: Cisco – the company who made the lovely shield kit, are now doing a kickstarter for a Pi version with a lot more red or white LEDs that plugs directly into the GPIO.