Posts Tagged ‘Arduino’

Arduino + Processing – Make a Radar Screen to Visualise Sensor Data from SRF-05 – Part 1: Setting up the Circuit and Outputting Values

arduino servo SRF05

First things first, we need to build our circuit. This is the easy bit! We’ll be using the Arduino to control a servo that will rotate our sensor around 180 degrees. The Arduino will then send the value from the distance sensor along with the current angle of the servo to the serial port.

Before proceeding please take a moment to check out some of my other work with the SRF-05 and servos if you’re unfamiliar with either.
Arduino SRF-05 Tutorials
Arduino Servo Tutorials

I’m building this with the SRF-05 ultrasonic range finder/ distance sensor, but because this has a fairly wide field of detection it’s not very precise – I think I’ll end up trying a different range finder maybe an IR one as the SRF-05 works best as a static sensor/ detector, anyway…

Arduino Radar Parts list

SRF05 Ultrasonic range finder
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
1x Servo (has to need no more than 5v supply)
You’ll also need some way to mount the sensor to the servo.

Arduino Radar Servo Circuit

Straight forward, we have the Arduino providing power to the breadboard and we have the servo and the SRF-05 sharing this power. Then we have the servo output pin going to Arduino digital pin 9 and the SRF-05 pins going to digital pin 2 and 3. You’ll notice that in my pictures I have 2 servos – I’m just using the bottom one of the pair to rotate the sensor round. On your servo you’ll need to figure out a way to mount the sensor on to the servo wheel – I used a lot of blu-tac! You’ll also see I’ve mounted my sensor vertically so that the when the servo moves there’ll be less interference with recieving values – placing the sensor horisontally seemed to give differences of up to and sometimes over 5cm between the first and second readings.

My servos do tend to move a bit so I’ve used more blu-tak/ modelling clay to hold them down and in place – if the servos move other than the way they’re meant to then it means dodgy readings.

SRF05 pin layout
arduino-servo-SRF05
Simple rig to rotate sensor 180 degrees

Arduino SRF05 Radar Sketch

The hardest bit – rotate the servo from left to right, then right to left and for every degree of movement take a series of readings and send them to the serial port. We’ll want to produce an average reading value for consistancy. Unfortunately with this ultrasound sensor we have to be quite slow to make sure we’re getting accurate values and we have to allow time for the signal to come back each time and register in order to produce the average value.

We do the rotation using a for loop to count to 180 and for each iteration we move the servo by +1 or -1 depending on which way we’re going – if you’ve hacked your servos then you can do a full 360 loop. During this loop we do another FOR loop to count to 10/ numReadings and for each iteration we add the distance measured to the total and after 10 readings we get our average by dividing the total by the number of readings. Then reset the total and the counter to start again for the next servo position. Finally before finishing the  the FOR loop for the servo we output the servo position and average reading to the serial port each with a preceeding character for us to later use to identify the values when reading the serial port in Processing. The last line is using println which will start a new line for the next set of values – each reading has its own line in the serial buffer makign it much easier to get our values back out.

/*
luckylarry.co.uk
Radar Screen Visualisation for SRF-05
Sends sensor readings for every degree moved by the servo
values sent to serial port to be picked up by Processing
*/
#include             // include the standard servo library
Servo leftRightServo;         // set a variable to map the servo
int leftRightPos = 0;         // set a variable to store the servo position
const int numReadings = 10;   // set a variable for the number of readings to take
int index = 0;                // the index of the current reading
int total = 0;                // the total of all readings
int average = 0;              // the average
int echoPin = 2;              // the SRF05's echo pin
int initPin = 3;              // the SRF05's init pin
unsigned long pulseTime = 0;  // variable for reading the pulse
unsigned long distance = 0;   // variable for storing distance

/* setup the pins, servo and serial port */
void setup() {
  leftRightServo.attach(9);
  // make the init pin an output:
  pinMode(initPin, OUTPUT);
  // make the echo pin an input:
  pinMode(echoPin, INPUT);
  // initialize the serial port:
  Serial.begin(9600);
} 

/* begin rotating the servo and getting sensor values */
void loop() {
  for(leftRightPos = 0; leftRightPos < 180; leftRightPos++) {  // going left to right.
    leftRightServo.write(leftRightPos);
      for (index = 0; index<=numReadings;index++) {            // take x number of readings from the sensor and average them
        digitalWrite(initPin, LOW);
        delayMicroseconds(50);
        digitalWrite(initPin, HIGH);                           // send signal
        delayMicroseconds(50);                                 // wait 50 microseconds for it to return
        digitalWrite(initPin, LOW);                            // close signal
        pulseTime = pulseIn(echoPin, HIGH);                    // calculate time for signal to return
        distance = pulseTime/58;                               // convert to centimetres
        total = total + distance;                              // update total
        delay(10);
      }
    average = total/numReadings;                               // create average reading

    if (index >= numReadings)  {                               // reset the counts when at the last item of the array
      index = 0;
      total = 0;
    }
    Serial.print("X");                                         // print leading X to mark the following value as degrees
    Serial.print(leftRightPos);                                // current servo position
    Serial.print("V");                                         // preceeding character to separate values
    Serial.println(average);                                   // average of sensor readings
  }
  /*
  start going right to left after we got to 180 degrees
  same code as above
  */
  for(leftRightPos = 180; leftRightPos > 0; leftRightPos--) {  // going right to left
    leftRightServo.write(leftRightPos);
    for (index = 0; index<=numReadings;index++) {
      digitalWrite(initPin, LOW);
      delayMicroseconds(50);
      digitalWrite(initPin, HIGH);
      delayMicroseconds(50);
      digitalWrite(initPin, LOW);
      pulseTime = pulseIn(echoPin, HIGH);
      distance = pulseTime/58;
      total = total + distance;
      delay(10);
    }
    average = total/numReadings;
    if (index >= numReadings)  {
      index = 0;
      total = 0;
    }
    Serial.print("X");
    Serial.print(leftRightPos);
    Serial.print("V");
    Serial.println(average);
   }
}

[ad#Google Ad in content]

Part 2: Visualising the Data
Part 3: Visualising the Data from Sharp Infrared Range Finder

Arduino – Basic Theremin meets Processing!

Arduino piano theremin

My last theremin involved a small speaker. Now I’ve replaced the speaker with my PC, using processing to pick up the values from the SRF05 ultrasound sonar distance sensor and play different notes accordingly – which gives multiple possibilities and far better sounds.

So to start with check out my previous theremin, the circuit is the same except for removing the speaker and the Arduino code now prints values to the serial port instead of outputing directly to a speaker. The only thing that I’m doing here that is really new is using the minim libary for Processing, built by this chap (thankyou). What this allows us is to assign a sound file to a variable in Processing and then gives us functions to start/stop the sound.

In my processing code you’ll see that I’ve got 12 sounds, one for each chromatic note and at the moment they’re from a piano. To get sounds and samples to use you can sign up to freesound.org. Mine I got here from ‘pinkyfinger’ and once you’ve decided which sounds you want to use then the rest is fairly easy – the more samples and octaves the better. I’ve used the piano set here just so I can hear the different notes and I’ve only 12 notes (chromatic scale) but eventually Iwould like to expand this to say 48 notes.

When you get your sounds I’ve found it’s easiest to use .wavs but minim will allow you to use WAV, AIFF, AU, SND, and MP3 files. Also I store my sounds in the root of the folder where I’m saving my processing sketch.

Ok, lets start with the Arduino parts, circuit and sketch.

Arduino Theremin Parts

SRF05 Ultrasonic range finder
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board (you can actually do this without a breadboard)
Jumper/ Connector wires

The Theremin Arduino Circuit

Basically the same as before just without the speaker on it. For more info on the SRF05 checkout my past stuff here. In this instance Processing is going to do all the work, so the circuit just needs to pass values from the SRF05 to Arduino, which in turn passes values to my PC via the USB cable.

piano-theremin

The Arduino Theremin Sketch

Very cut down version, it takes the value as before and converts it to a distance and then just prints it to a new line in on the serial port.

// written at: luckylarry.co.uk
// very easy Theremin combined with processing
// sketch prints out distance to the serial port
// processing picks up value and plays notes accordingly
// no annoying speaker drone! 🙂

// setup pins and variables for SRF05 sonar device
int echoPin = 2;                                // SRF05 echo pin (digital 2)
int initPin = 3;                                // SRF05 trigger pin (digital 3)
unsigned long pulseTime = 0;                    // stores the pulse in Micro Seconds
unsigned long distance = 0;                     // variable for storing the distance (cm) we'll use distance as a switch for the speaker

//setup
void setup() {

  pinMode(initPin, OUTPUT);                     // set init pin 3 as output
  pinMode(echoPin, INPUT);                      // set echo pin 2 as input
  Serial.begin(9600);                           // start the serial port

} 

// execute
void loop() {
  digitalWrite(initPin, HIGH);                  // send 10 microsecond pulse
  delayMicroseconds(10);                        // wait 10 microseconds before turning off
  digitalWrite(initPin, LOW);                   // stop sending the pulse
  pulseTime = pulseIn(echoPin, HIGH);           // Look for a return pulse, it should be high as the pulse goes low-high-low
  distance = pulseTime/58;                      // convert the pulse into distance (cm)

  // make the sound.
  // check the distance, if over 50cm make no sound - send no signal
  if (distance > 50) {
    Serial.println(distance);                   // print the distance value to the serial port
    delay(50);                                  // delay for 50 milliseconds before starting again...
  }
}

[ad#Google Ad in content]
Next up we have processing, which will look for values on the serial port, so first upload the Arduino code to your board and test it works. Next start up Processing to finish off the code. If like me you’re fairly new to processing there’s lots of info to be had at: http://www.arduino.cc/playground/Interfacing/Processing

The Processing Theremin Sketch

With your code now running on the Arduino board we now need processing to pick up these values. Previously I had something of an issue getting these values and reading them. But in hindsight I was being a bit dim when I realised I could just look in the serial port for when a new line (n) was printed which would tell me that a new value was about to be sent. Of course thats providing your Arduino sketch is using Serial.println() (print line) instead of Serial.print() which just chucks every value into one long string – and if you look at my previous attempts with processing you can laugh at how I started splitting this huge string up etc… Oh hindsight is a wonderful thing, anyway, I digress, below is the processing sketch:

// written at: luckylarry.co.uk
// very easy Theremin combined with processing
// sketch prints out distance to the serial port
// processing picks up value and plays notes accordingly
// no annoying speaker drone! 🙂 replace the sounds and delays with
// your own...

import processing.serial.*;                // import serial library so we can read the serial port
import ddf.minim.*;                        // import minim library

// define the serial port
Serial myPort;          

// define minim variables:
// here we say that variable A is an audiosample etc...
Minim minim;
AudioSample GSharp;
AudioSample A;
AudioSample Bb;
AudioSample B;
AudioSample C;
AudioSample CSharp;
AudioSample D;
AudioSample Eb;
AudioSample E;
AudioSample F;
AudioSample FSharp;
AudioSample G;

// setup
void setup () {

  // set up the variables, loading in the sound files from your project folder
  // which should be the same place as where you save this sketch
  // details on using minim and audioSample are here: http://code.compartmental.net/tools/minim/manual-audiosample/
  minim = new Minim(this);
  GSharp = minim.loadSample("GSharp.wav", 2048);
  A = minim.loadSample("A.wav", 2048);
  Bb = minim.loadSample("Bb.wav", 2048);
  B = minim.loadSample("B.wav", 2048);
  C = minim.loadSample("C.wav", 2048);
  CSharp = minim.loadSample("CSharp.wav", 2048);
  D = minim.loadSample("D.wav", 2048);
  Eb = minim.loadSample("Eb.wav", 2048);
  E = minim.loadSample("E.wav", 2048);
  F = minim.loadSample("F.wav", 2048);
  FSharp = minim.loadSample("FSharp.wav", 2048);
  G = minim.loadSample("G.wav", 2048);

  // List serial ports, saves us trying to figure out which COM we're using.
  println(Serial.list());
  // Open the active port - providing you've only got one sending serial data (which you should)
  myPort = new Serial(this, Serial.list()[1], 9600);
  // don’t read the serial buffer until we see a new line - this is genius and simple compared with my last efforts
  myPort.bufferUntil('n');
}

void draw() {
  // we need to declare the draw function even though we're not using it!!
}

void serialEvent (Serial myPort) {
  // get the string from the serial buffer - gets all chars until the next line break...
  String bufferString = myPort.readStringUntil('n');

  if (bufferString != null) {
    // get rid of any whitespace - sometimes the serial buffer can have blanks etc.. in the string
    bufferString = trim(bufferString);
    // convert the value to an int - we're only sending numbers over the serial port so parsing it to an int shouldn't ever be an issue.
    float inByte = float(bufferString);
    int pulse = int(bufferString);         // declare a variable to hold our value.
    println(pulse);                        // for debug print the value so we can check it.

    // remember that our pulse is in CM so if its less than 5cm then do this etc... else do this... else do this.. for as many sound samples
    if ( pulse < 5 ) {
      GSharp.trigger();
      delay(25);
    }
    else if ( pulse < 8 ) {
      A.trigger();
      delay(25);
    }
    else if ( pulse < 11 ) {
      Bb.trigger();
      delay(25);
    }
    else if ( pulse < 14 ) {
      B.trigger();
      delay(25);
    }
    else if ( pulse < 17 ) {
      C.trigger();
      delay(25);
    }
    else if ( pulse < 20 ) {
      CSharp.trigger();
      delay(25);
    }
    else if ( pulse < 23 )  {
      D.trigger();
      delay(25);
    }
    else if ( pulse < 26 ) {
      Eb.trigger();
      delay(25);
    }
    else if ( pulse < 29 ) {
      E.trigger();
      delay(25);
    }
    else if ( pulse < 32 ) {
      F.trigger();
      delay(25);
    }
    else if ( pulse < 35 ) {
      FSharp.trigger();
      delay(25);
    }
    else if ( pulse < 38 ) {
      G.trigger();
      delay(25);
    }
    else if ( pulse > 50 ) {
      // if the distance is greater than 50cm then play nothing
    }

  } // end if there's a value in the serial bufferstring

}   // end void serialevent()

[ad#Google Ad in content]

Arduino – A Basic Theremin

basic theremin

Theremins are cool. Fact. You may also have heard of them as either aetherphone/ etherophone or termenvox/ thereminvox. Essentially its an electronic music instrument that plays a certain note depending on the position of your hand and its distance from an antenna.

Building a very basic one with Arduino is easy – easier than my basic Arduino drum machine. Very easy. Basically we can replicate one by building a circuit of a speaker and a distance sensor, such as my favourite the SRF05 ultrasound thingy. We calculate the distance and the nearer you get the difference in note/frequency emitted from the speaker.

You’re going to need only a few parts and not much code. You can read more about my applications of the SRF05 along with sample code here: Arduino SRF05 Projects. If you can’t be arsed with reading any of that then no worries all is revealed below…

Arduino Theremin Parts List

1x speaker
SRF05 Ultrasonic range finder
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires

Arduino Theremin Circuit

Very simple,we have a speaker with the negative running to Arduino’s GND, and it’s positive going to digital pin 6 on the Arduino board. The code will tell the speaker to turn on and off rapidly based on the objects distance from the ultrasound sensor. This rapid turning on and off of the speaker is what will generate different sounds (like my drum machine). The only other part of the circuit is the SRF05 distance/ proximity sensor. It has a positive and negative connected to the Arduino and then 2 pins for trigger and echoing an ultrasound wave both going to digital pins 2 and 3 respectively on the Arduino board.

basic-theremin-circuit

Theremin Arduino Sketch

To save the annoyance of those around you I’ve added in a small statement that basically says if your hand is not within 30 cm of the sensor then don’t play a sound. But otherwise basically we measure distance constantly and when an object is detected we convert the distance in to a value for which to use in the oscillation of the speaker to generate different pitchs and frequencies.

// written at: luckylarry.co.uk
// very easy Theremin

// setup pins and variables for SRF05 sonar device
int echoPin = 2;                                // SRF05 echo pin (digital 2)
int initPin = 3;                                // SRF05 trigger pin (digital 3)
int speakerPin = 6;                             // Speaker pin
unsigned long pulseTime = 0;                    // stores the pulse in Micro Seconds
unsigned long distance = 0;                     // variable for storing the distance (cm) we'll use distance as a switch for the speaker
unsigned long soundDelay = 0;                   // variable for storing the deay needed for the pitch

//setup
void setup() {

  pinMode(speakerPin, OUTPUT);                  // sets pin 6 as output
  pinMode(initPin, OUTPUT);                     // set init pin 3 as output
  pinMode(echoPin, INPUT);                      // set echo pin 2 as input

 } 

// execute
void loop() {
  digitalWrite(initPin, HIGH);                  // send 10 microsecond pulse
  delayMicroseconds(10);                        // wait 10 microseconds before turning off
  digitalWrite(initPin, LOW);                   // stop sending the pulse
  pulseTime = pulseIn(echoPin, HIGH);           // Look for a return pulse, it should be high as the pulse goes low-high-low
  distance = pulseTime/58;                      // convert the pulse into distance (cm)
  soundDelay = pulseTime/3;                     // alter this variable to alter the pitch of the sound emitted

  // make the sound.
  // check the distance, if over 30cm make no sound
  if (distance < 30) {
  digitalWrite(speakerPin, HIGH);
  delayMicroseconds(soundDelay);
  digitalWrite(speakerPin, LOW);
  delayMicroseconds(soundDelay);
  }
}

[ad#Google Ad in content]

Pretty cool for no parts - but of course the sound quality isn't great. I guess you could add a switch in the circuit so you could manually start and stop it to produce clearer notes.

Arduino – Basic Persistance of Vision

arduino x pov

I think this’ll be the start of a few more projects for me. I’ve seen some cool LED PoV stuff (Persistance of Vision) with mounting displays on bikes, so hopefully I’ll get round to doing something like that.

Anyway as a start I’ve got 5 LED’s connected to 5 pins on the Arduino, nothing complex there. The real struggle is to work out the timings, or rather the pauses between the patterns. Starting with how to make a character or drawing.

Arduino POV LED parts

Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
5 x LED (All the same colour!)
5 x 220 Ohm resistor (Red, Red, Brown, Gold)

Using my knowledge of graphics etc.. the logical way to do this is to use a grid of pixels and I’ll have the column of LED’s change quickly to represent each column of the grid or frame. The effect will be that at a certain speed this should look like a grid of of LED’s rather than a lonely column.

So we have a grid as below:

pin 3: 10001
pin 4: 01010
pin 5: 00100
pin 6: 01010
pin 7: 10001

This shows a cross drawing, but you can make letters or drawings etc.. once you figure this out. This is the hardest bit of the process to grasp and I’ll try and explain the code.

We need to first set our LED’s as an output, the number of LED’s is how many rows are in your grid, once this is done we need to define how many columns are in our grid.

Then we define an array of a sequence of 0’s and 1’s to say when to turn on and off the LED’s and we use a for loop to run through the number of rows against the array. After this count is finished we then loop through the number of columns to move on to the next chunk of the array. If the array is a 0, then LED is low otherwise set it to HIGH. Until we reach the end of the array and we start again. You should be able to see/ understand this from my code comments below. If you want to add more letters then you can add in another frame, just keep adding to the sequence though.

Arduino LED POV Circuit

Nothing too fancy just 5 LED’s in a line (longer terminal is +, shortest is – ), a 220 Ohm resistor between the + pin and the Arduino pin and the – pin going to GND on the Arduino.

arduino-x-pov-layout

LED Persistance of Vision Code

int setPins[] = {7,6,5,4,3};      // an array of pins/ outputs for the LEDs
int rows = 5;                   // number of LED's
int columns = 5;                // number of columns
int numberOfFrames = 1;         // number of frames

// 10001
// 01010
// 00100 = the array of 1,0,0,0,1, 0,1,0,1,0, 0,0,1,0,0, 0,1,0,1,0, 1,0,0,0,1
// 01010
// 10001
// draws a cross: 1,0,0,0,1 = pin3 on, pin4 off, pin5 off, pin6 off, pin7 on etc... count to the number of rows (5) then start again at pin3.
// repeat. add to this to add more letters

int drawing[] = {1,0,0,0,1, 0,1,0,1,0, 0,0,1,0,0, 0,1,0,1,0, 1,0,0,0,1}; 

void setup()
{
        // for each pin set in the array set it as an output
        for (int countPins = 0; countPins < rows; countPins++) {
                pinMode(setPins[countPins], OUTPUT);
        }
}

void loop()
{
        // for each frame/ drawing
        for (int countFrames = 0; countFrames < numberOfFrames; countFrames++)
        {
                // loop through each column
                for (int countColumns = 0; countColumns < columns; countColumns++)
                {
                        // then loop through each row in each column
                        for (int countRows = 0; countRows < rows; countRows++)
                        {
                                // figure out if the LED is meant to be on or off
                                // find the value of the item in the drawings array
                                // based on the counts to get the array position
                                if (drawing[countFrames*columns*rows + countColumns*rows + countRows] == 0)
                                {
                                        digitalWrite(setPins[countRows], LOW);
                                } else {
                                        digitalWrite(setPins[countRows], HIGH);
                                }
                        }
                        delay(5); // delay between showing each column
                }

                // then turn off all LED's
                for (int countRows = 0; countRows < rows; countRows++)
                {
                        digitalWrite(setPins[countRows], LOW);
                }
                delay(15); // delay between showing each frame.
        }
        delay(0); // delay between drawings. Set this depending on speed of movement
}

[ad#Google Ad in content]

When you're done go to a dark room and shake the circuit to see the X form - I bundled the Arduino and breadboard along with a 9v battery together using an elastic band.

Arduino – Getting my LCD Screen to work.

arduino lcd screen

[ad#Google links]

I’ve gotten hold of what I assumed was a compatible 16×2 LCD screen with my Arduino board – it’s a Powertip PC1602F and uses a compatible display driver for the Hitachi HD44780 display chip. This is essentially what the Arduino LCD libraries are built around, so when I failed to get a display this is the first thing that I checked out. I also downloaded and installed Arduino 0017 which has a better and more up to date library for LCD stuff but you can update version 0015 with this library I think.

Unfortunately this LCD screen also cost me my first Arduino board, not sure if it was coindence or not, but the USB chip burnt out when I was connecting the LCD screen via various guides and the manufacturers pin layouts. Also turns out that you don’t actually need to use all the pins – for a start my screen isn’t back lit and you only need 4 out of the 8 jumpers.

Anyway, one new Arduino board later and I wire in my display and all I would get is a line of solid block characters, so it was working and I had tried various code snippets and Arduino versions but no luck in getting any text on the screen. Occaisonally I would also get a faint cursor or no display at all – which freaked me out slightly considering i had already potentially lost an Arduino board to this LCD screen and it was beginning to frustrate me.

So now I went for broke – I soldered some jumper wires on to the LCD board pins and hey presto when any program is run text is now displayed, although at first my connections weren’t great so makesure you solder the pins really well with no bridges! Turns out that whilst the wire ends fit snug in the LCD pin holes they still don’t form a decent connection and this was causing it to have random results. For whatever reason, I decided to leave the rubber ends on the jumper wires, but this seems to have turned out fine.

Now I just have to figure out what to do with the LCD screen! Below is the sketch that I used along with a picture of the wiring – I would recommend that you use as many different colour wires as possible for this as you could have up to 16 wires running from this board so you want save on any confusion as much as possible.

Arduino LCD Display Circuit

I didn’t bother using a potentiometer to control the contrast on the screen as recommended, so I stuck that pin to GND which seemed to work fine for the display. Other than that this is the standard circuit from the tutorials here

Arduino LCD Wiring:

arduino-lcd-screen-layout-key

Arduino LCD Display Sketch

/*
  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
 * 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 25 July 2009
 by David A. Mellis

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

// include the library code:
#include

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of rows and columns:
  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);
}

[ad#Google Ad in content]

Obstacle avoidance Arduino robot – build your own larryBot

larryBotv06

So after 5 previous versions that had various flaws, I now have an Arduino robot that actually works and although basic is very cheap – although there a probably a few more flaws so please point them out to me but this is a good start on how to make your own robot.

In order to catch up, please see my previous posts below, describing the problems that the other 5 versions had, how the h-bridge chip works and using the SRF05 ultrasound distance sensor.

larryBot – Arduino robot versions 0.1 to 0.5 lessons learned
Control a DC motor with Arduino and L293D chip

Arduino SRF05 Distance Sensor

Now that you’re up to speed, lets start by fixing the flaws in the previous version, this was the case that my motors were drawing way too much current and the L293D chip from ST Micro couldn’t output enough current for each motor.

So, I replaced the chip with the snappy named ‘SN754410‘ from Texas Instruments. This has EXACTLY the same 16 pin layout as the L293D chip and all of the same features except that it can output 1.2 amps per channel rather than the now tiny 0.6 amps of the L293D. Pin configuration diagram below is the same for the L293D as it is for the SN754410, I recommend the SN754410 Arduino comination.

L293D Pin layout

Great I’ve now got more current to my motors, but their stall current is still at over 2 amps, I could add a heatsink to the chip and pass more current through it, but instead I got some more efficient motors than the Mabuchi FA-130’s that came with the Tamiya gearbox. These motors are made by Solarbotics and are their RM3 series which fit perfectly, can handle 4 times the voltage but use a fraction of the current – typically at 9v they use just over 1 amp. Perfect.

Having corrected this, larryBot v0.6 was go! I still faced a lack of power to the DC motors – either because my batteries were running low or not able to supply the current. But since my new motors could run up to 12 volts (instead of the puny 3v of the originals) I decided to use a 9v battery to power them instead of my 4 AA’s.

Watching larryBot move is great, even on carpet and with the tank tracks 9 times out of ten he can climb small obstacles or has enough traction to shunt them out the way. Anyway enough waffling – here’s how he’s made…

The Arduino Robot Tracked Chassis

You could use anything you want really – construction sets, your own custom fabricated chassis etc… But since I’m cheap I managed to get a pile of foamboard for my chassis. I can waste and reuse as much of this as I want so its no problem if I make a mistake or want to improve it. Also in theory this leads to rapid prototyping, so when I do decide to fabricate a chassis I know exactly where the best places are for holes, mounts etc…

The robot chassis parts and tools:

Small Phillips/ cross-head screwdriver
Gluegun
Craft knife
Pencil
Ruler
Assorted nuts and bolts – A good set of M series nuts and bolts
Foamboard 5mm thick – 1 A4 sheet is plenty
Tamiya gearbox 70097 – assembled in mode A
Tamiya track and wheel set 70100
Elastic bands (normally dropped by the postie)

Sizing up the robot base

First of all the size of our chassis design is dictated by a few things. The axle length: our tank tracks need about 5mm clearance so the space on the axle is roughly 65mm wide that I can mount on. Next we have the length of the tracks and how many wheels will be used, I kept my track footprint small so my chassis length didn’t need to be much bigger than the gearbox. Which leads on to gearbox positioning – the Tamiya gearbox I have is roughly 75mm in length and the shape of the tracks will dictate where to position the gearbox as the driving wheels are attached to this. The final consideration of course is mounting all the sensors, battery packs, breadboard and the Arduino board.

In my attempts so far I have a base that is just longer than twice the length of the gearbox (175mm) which gives me space at the front for sensors and space at the back for batteries. I then mount a smaller piece of foamboard on top of this that then houses the gearbox and spaces it far enough above the running wheels for the tracks at the bottom – also giving enough tension in the tracks for them not to slip off (unlike larryBot v0.4). From here I can continue to bolt on additional structures to position the breadboard and so on.

So using this knowledge you should be able to size up and cut the foamboard to the dimensions you need – a craft knife will be more than enough to cut this board. To make the holes needed for your screws and bolts just use a small Phillips/ Cross-head screwdriver to bodge a hole through – it won’t take any effort, then you can drive the screws through this guiding hole. If you have washers then use them but the foamboard seems to be able to support all the hardware fine.

Attaching the running wheels and tank tracks

First mark out the position of where you want your wheels, very important as you don’t want them wonky!

larryBotv06-base

To mount the running wheel axles on to the chassis I used a couple of small hexagonal bolts for each side of the axle and then used the glue gun to fix them to the chassis – the best way to do this is to put the bolts on to the axle, use a small amount of glue to hold the bolts in place and then use a shit load of glue over the bolts to secure them properly.

When adding the wheels to the axles, don’t push them all the way on as these axles are slightly shorter than the Tamiya gearbox which will cause you problems with the tracks.

Mounting the Tamiya gearbox, DC motors, sensors, breadboard, Arduino and batteries

To attach the gearbox I just used the screws supplied with the gearbox and bolted this to my smaller piece foamboard. I then in turn bolted this to the main chassis using 4 long bolts and a series of spacers and nuts in between the layers to given the correct spacing and adjustment for my drive wheels.

For the SRF05 distance sensor I just used some blu-tack/ modelling plasticine to hold it in place for now.

The breadboard I mounted above the gearbox, which for this I just fixed it on top of 4 long bolts which then in turn attached the gearbox base. The Arduino board currently then sits on the breadboard held on by the multitude of wires running from it and the power supply cable.

And for the batteries, since I scrapped using the 4xAA’s to power the motor I only had to worry about two 9V batteries, 1 of which was my DC power supply for the board. I fixed them to the chassis just using an elastic band, since I’d want to get to them easily enough.

larryBotv06-finished

Simple Arduino Robot Circuit

The parts list doesn’t differ much from my other tutorials for motors and L293D. But I did find it was troublesome to get the parts from the same supplier, so be aware that you may need to look at multiple suppliers and postage may get expensive.

Robotic parts list

2 x Solarbotics RM3 motors
SN754410 motor driver chip
SRF05 Ultrasonic distance sensor
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
2x 220nF multilayer ceramic capacitor (Y5V)
2 x 50V 10uF Capacitor (although I’ve not used them here)
2.1 mm coaxial DC jack
2 x PP3 9Volt battery
PP3 9Volt Connector
9Volt battery holder

larryBotv06-board

You can see that the circuit is pretty simple, nothing actually that fancy, I have the SRF05 using the +5v, GND and digital pins 12 and 13. The SN754410 then uses the digital pins 9 and 10 to control each channel – these can use PWM to do speed control, then there are the switch pins on the h-bridge that go to digital pins 3,4,5 and 6. The spare GND is used to join the GND connection between the motor power and Arduino power supply. Here are the instructions for the 9v battery DC supply. If you want to use the extra 50v 10 uF capacitors then these sit on the power supply for pins 8 and 16 on the SN751140 respectively.

larryBotv06-SN754410-layout

Arduino Robot Code

Nothing much has changed from the larryBot v0.1-0.5 sketch except that I’ve altered the detection distances as I have a much faster response time from the robot.

const int numOfReadings = 10;                   // number of readings to take/ items in the array
int readings[numOfReadings];                    // stores the distance readings in an array
int arrayIndex = 0;                             // arrayIndex of the current item in the array
int total = 0;                                  // stores the cumlative total
int averageDistance = 0;                        // stores the average value

// setup pins and variables for SRF05 sonar device

int echoPin = 12;                               // SRF05 echo pin (digital 2)
int initPin = 13;                               // SRF05 trigger pin (digital 3)
unsigned long pulseTime = 0;                    // stores the pulse in Micro Seconds
unsigned long distance = 0;                     // variable for storing the distance (cm)

int motor1Pin1 = 3;                             // pin 2 on L293D
int motor1Pin2 = 4;                             // pin 7 on L293D
int enable1Pin = 9;                             // pin 1 on L293D
int motor2Pin1 = 5;                             // pin 10 on L293D
int motor2Pin2 = 6;                             // pin  15 on L293D
int enable2Pin = 10;                            // pin 9 on L293D

void setup() {
  // set the motor pins as outputs:
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT);
  pinMode(enable1Pin, OUTPUT);
  pinMode(motor2Pin1, OUTPUT);
  pinMode(motor2Pin2, OUTPUT);
  pinMode(enable2Pin, OUTPUT);
  // set enablePins high so that motor can turn on:
  digitalWrite(enable1Pin, HIGH);
  digitalWrite(enable2Pin, HIGH);

  pinMode(initPin, OUTPUT);                     // set init pin 3 as output
  pinMode(echoPin, INPUT);                      // set echo pin 2 as input

  // create array loop to iterate over every item in the array

  for (int thisReading = 0; thisReading < numOfReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  digitalWrite(initPin, HIGH);                  // send 10 microsecond pulse
  delayMicroseconds(10);                                // wait 10 microseconds before turning off
  digitalWrite(initPin, LOW);                   // stop sending the pulse
  pulseTime = pulseIn(echoPin, HIGH);           // Look for a return pulse, it should be high as the pulse goes low-high-low
  distance = pulseTime/58;                      // Distance = pulse time / 58 to convert to cm.
  total= total - readings[arrayIndex];          // subtract the last distance
  readings[arrayIndex] = distance;              // add distance reading to array
  total= total + readings[arrayIndex];          // add the reading to the total
  arrayIndex = arrayIndex + 1;                  // go to the next item in the array                                 

  // At the end of the array (10 items) then start again
  if (arrayIndex >= numOfReadings)  {
    arrayIndex = 0;
  }

  averageDistance = total / numOfReadings;      // calculate the average distance
  delay(10);

  // check the average distance and move accordingly

  if (averageDistance <= 10){
    // go backwards
    digitalWrite(motor1Pin1, HIGH);
    digitalWrite(motor1Pin2, LOW);
    digitalWrite(motor2Pin1, HIGH);
    digitalWrite(motor2Pin2, LOW);    

  } 

  if (averageDistance <= 25 && averageDistance > 10) {
    // turn
    digitalWrite(motor1Pin1, HIGH);
    digitalWrite(motor1Pin2, LOW);
    digitalWrite(motor2Pin1, LOW);
    digitalWrite(motor2Pin2, HIGH);
  }
  if (averageDistance > 25)   {
    // go forward
    digitalWrite(motor1Pin1, LOW);
    digitalWrite(motor1Pin2, HIGH);
    digitalWrite(motor2Pin1, LOW);
    digitalWrite(motor2Pin2, HIGH);     

  }
}

[ad#Google Ad in content]

Some problems you may face – if like my you don’ t have a spare 9V battery connector to hand check this connection if nothing is happening – I used blu-tack to hold my wires in place so it’s a bit temperamental.
Check that your motor wires are properly in contact with the motor terminals if you haven’t soldered them again using some blu-tack or tape is handy for getting a good connection.
Motor’s are under strain – your tracks are too tight.
Tracks come away from the wheels – check your tracks are not too loose and that your running wheels are in line with the drive wheels – the Tamiya gearbox is slightly wider than the Tamiya track and wheel set axles.

larryBotv06-frontback

I’ve gotten a fairly cheap robot that avoids obstacles, next plan is to extend it to sense various things – for instance detect motion and move towards it, or a light/ heat source. The robot costs are quite high if you factor in the Arduino board and if you don’t have any of the parts – but this can be broken down and used for many other projects so you’ll get a lot of reuse out of these bits, but I reckon that the total cost is around £70-80 in total, so fairly cheap when compared to other bots. Of course if you don’t want tracks (?) then you can just use wheels instead, Tamiya do also make wheels that will fit the gearbox.

Just in case you have trouble getting parts, here’s a small list of people that can supply the various bits – although none of them will have the full set. Shipping from the states is an option, but check the shipping costs as it may negate the cost savings. Please let me know of other sources, the list is in no particular order.

Sparkfun – USA: motor controller and Tamiya parts
Pololu – USA: Tamiya parts and motors
Techbotics – UK: Tamiya parts – just about cheaper than getting parts from Sparkfun/ Pololu in the USA
Active robots – UK: motors, SRF05 but generally overpriced on everything
Rapid Electronics – UK/EU/USA: most component parts and hardware
Farnell – UK/EU/USA: SN754410 chip and most components but shit for orders if your billing and delivery addresses are separate
Mouser – UK/EU/USA: SN754410 chip and most components
SK Pang – UK: SN754410 chip but dodgy VAT calculations (charges tax on shipping as well) few other parts here.

If you need an Arduino board, I reliably found a seller on ebay from Hong Kong that will sell and ship you aboard for far less than paying for it the UK – downside is it takes about a week to arrive.

larryBot – Arduino robot versions 0.1 to 0.5 lessons learned

larryBotv01

So I’ve decided to build a robot using Arduino to control the sensors. Here’s my progress so far – I am hoping that my mistakes here and over the coming posts will guide people in more detail about what to avoid. Also I won’t provide a parts list until I have a working robot…

The purpose of my early version of larryBot is to create a basic robot that can be controlled with Arduino and that can be made from minimal materials and costs – I aimed with the Arduino included for this cost to be about £60-70 in total depending on what you can scrounge and providing you have the tools and some parts already. Also I wanted to make a robot from scratch rather than hacking together existing things, like modifying a RC car chassis for example. So far all larryBots aim is to do is to avoid obstacles and move around them.

First off I looked at using the L293D chip to control 2 DC motors and this would operate my steering and I would use the SRF05 ultrasound range finder as a proximity sensor. I had no problem with this circuit when I first started until today.

My first consideration was the chassis, now I figure that most people like me have spent the money on the Arduino board, which is worth every penny, and you probably have a few motors and bits with which to do this. However, like me, you looked at chassis and what to build one from to mount all the electronics. Theres the Tamiya erector set (if you can get it in the UK), Meccano, Lego and of course specific robot chassis’s not to mention designing your own and getting it made.

All very expensive (unless you have it already) and requires effort. I am lazy and karma happened to bless me with finding a stash of 5mm thick foamboard for me to use. If you aren’t aware foamboard is used for modelling and mounting work for display – if you need any then get a design agency to come and quote for work at your company and keep their foamboard 🙂

Anyway, the foamboard is excellent for my uses so far as my robots aren’t massive and their weight is minimal. It also allows me to rapidly prototype a chassis and layout without any costs – you can just push screws and bolts through to mount motors and use a glue gun to join parts. Another bonus is that you only need a craft knife to cut it.

To connect everything I just brought a set of various nuts and bolts to use along with a glue gun and thats it.

My circuit throughout has basically remained the same, I use a 6v power supply to power the L293D and the motors, and a 9V DC power supply to power the Arduino, which controls the L293D and reads the Ultrasound sensor. My changes so far have been on the chassis, motors, movement and gearing. The sketch for these versions has also remained the same which you can see detailed below:

larryBot v0.1-05 Arduino Robot Sketch

const int numOfReadings = 10;                   // number of readings to take/ items in the array
int readings[numOfReadings];                    // stores the distance readings in an array
int arrayIndex = 0;                             // arrayIndex of the current item in the array
int total = 0;                                  // stores the cumlative total
int averageDistance = 0;                        // stores the average value

// setup pins and variables for SRF05 sonar device

int echoPin = 12;                               // SRF05 echo pin (digital 2)
int initPin = 13;                               // SRF05 trigger pin (digital 3)
unsigned long pulseTime = 0;                    // stores the pulse in Micro Seconds
unsigned long distance = 0;                     // variable for storing the distance (cm)

int motor1Pin1 = 3;                             // pin 2 on L293D
int motor1Pin2 = 4;                             // pin 7 on L293D
int enable1Pin = 9;                             // pin 1 on L293D
int motor2Pin1 = 5;                             // pin 10 on L293D
int motor2Pin2 = 6;                             // pin  15 on L293D
int enable2Pin = 10;                            // pin 9 on L293D

void setup() {
  // set the motor pins as outputs:
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT);
  pinMode(enable1Pin, OUTPUT);
  pinMode(motor2Pin1, OUTPUT);
  pinMode(motor2Pin2, OUTPUT);
  pinMode(enable2Pin, OUTPUT);
  // set enablePins high so that motor can turn on:
  digitalWrite(enable1Pin, HIGH);
  digitalWrite(enable2Pin, HIGH);

  pinMode(initPin, OUTPUT);                     // set init pin 3 as output
  pinMode(echoPin, INPUT);                      // set echo pin 2 as input

  // create array loop to iterate over every item in the array

  for (int thisReading = 0; thisReading < numOfReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  digitalWrite(initPin, HIGH);                  // send 10 microsecond pulse
  delayMicroseconds(10);                                // wait 10 microseconds before turning off
  digitalWrite(initPin, LOW);                   // stop sending the pulse
  pulseTime = pulseIn(echoPin, HIGH);           // Look for a return pulse, it should be high as the pulse goes low-high-low
  distance = pulseTime/58;                      // Distance = pulse time / 58 to convert to cm.
  total= total - readings[arrayIndex];          // subtract the last distance
  readings[arrayIndex] = distance;              // add distance reading to array
  total= total + readings[arrayIndex];          // add the reading to the total
  arrayIndex = arrayIndex + 1;                  // go to the next item in the array                                 

  // At the end of the array (10 items) then start again
  if (arrayIndex >= numOfReadings)  {
    arrayIndex = 0;
  }

  averageDistance = total / numOfReadings;      // calculate the average distance
  delay(10);

  // check the average distance and move accordingly

  if (averageDistance <= 25){
    // go backwards
    digitalWrite(motor1Pin1, HIGH);
    digitalWrite(motor1Pin2, LOW);
    digitalWrite(motor2Pin1, HIGH);
    digitalWrite(motor2Pin2, LOW);    

  } 

  if (averageDistance <= 45 && averageDistance > 25) {
    // turn
    digitalWrite(motor1Pin1, HIGH);
    digitalWrite(motor1Pin2, LOW);
    digitalWrite(motor2Pin1, LOW);
    digitalWrite(motor2Pin2, HIGH);
  }
  if (averageDistance > 45)   {
    // go forward
    digitalWrite(motor1Pin1, LOW);
    digitalWrite(motor1Pin2, HIGH);
    digitalWrite(motor2Pin1, LOW);
    digitalWrite(motor2Pin2, HIGH);     

  }
}

[ad#Google Ad in content]

I’ve gone down the route so far of using differential steering, this means that to turn left 1 motor goes forward while the other goes in reverse. I did look at using a servo to mimic an RC cars steering but this added to complexity which for now I want to avoid.

larryBot v0.1 – 0.2

This version had two rear mounted wheels that turned either way via the L293D motor driver giving me differential steering. I also mounted a single axle at the front with 2 wheels on this. At first this one moved fine on a smooth floor but then I noticed the motor mounted wheels were slipping so I bonded them to the axle using some araldite (strong glue). This was going fine but then I noticed that when used on a different surface larryBot couldn’t turn as effectively.

larryBot v0.3

So I figured that perhaps it was the fact that the steering would be limited by having 2 front wheels, so I removed these and built in a single wheel at the front for the bot to pivot on to aid steering. Saddly this wasn’t happening and larryBot still had problems on carpet. Next I looked at the motors, essentially they were just tranferring power to the wheels via a worm gear. This isn’t really any good to get any decent torque out of the motors, so perhaps a better gear system would help me out here. I also figured that realistically wheels may not be that great for the best transport, so I looked instead at getting some tracks.

larryBot 0.4

To keep costs down I spent a while looking for a small gearbox system and track set. Logically and costwise I arrived at the decision to get a Tamiya gearbox (Tamiya part No. 70097) with motors included and a Tamiya track and wheel set (70100), the total for which including postage was about £25 you can order from the states but there are a few places in the UK that you can order from too.

I created a long wheel base much like a standard tank and mounted everything on to a new chassis cut from foamboard – nothing complicated, just a rectangle with some bolts to hold the gear box on. To add the axles to the chassis, I used some nuts and glued them on to the chassis with the glue gun to create a way to hold the axles in place.

This worked out great – larryBot conquered the carpet! Hooray! But now with the gearbox he was too fast and kept throwing his tracks off the wheels when ever he turned so he never seemed to run for more than a few seconds – no where near as long as the previous versions. Back now to rethink the wheel base and track setup.

larryBot v0.5

So today I made a new chassis, much shorter wheel base and the tracks are much tighter, tested it with the motors wired up to the battery directly and larryBot now turns fine!

I added in the circuit board and larryBot started to run BUT… the motors began to cut out frequently and the L293d chip began to get very hot. Hmmmm…. It turns out that the motors supplied with the Tamiya gear box which are Mabuchi FA-130’s draw up to 2.2A stall current per motor! the L293D chip can only deliver a maximum of 0.6A to the motor which is barely enough to freely run the motor and with tracks on this will run the motor for less than 5 seconds before cutting out

So now it looks like I have 2 choices and I think I will do both – firstly I’ll look at a new motor driver chip which can handle higher current loads and secondly I’m going to replace the gearbox motors with a motor which has a much lower stall current than the huge 2A! This will also have a nice bonus of making my batteries last longer as well as my components – perhaps also allowing me to use just 1 power supply.

Now I need new motors/ control chip

Now I need new motors/ control chip, he

Arduino & Processing – Getting values from SRF05 ultrasound sensor & serial port

arduino processing

I’ve started to delve into Processing and passing values between Processing and Arduino. If you’re wondering what Processing is, basically its an open source programming language for vizualising data that can interface with Arduino either by reading values/ pins or by setting them. Just remember that they are 2 very different things and require 2 different sketches!

This is very cool if you want to display information from Arduino in a graphical way, or if you want to have a physical input device for your computer, for instance a Flash application that takes inputs from switches and potentiometers.

So anyway, it’s really very easy to get this installed and working, just do the following steps here: http://www.arduino.cc/playground/Interfacing/Processing

Now, I’ve had a bit of an issue getting values from my SRF05 from Arduino to Processing. In Arduino it works fine and the serial port shows the values correctly but in Processing I couldn’t get the values. Some people suggest using Firmata but the trouble with this is that it has very few of the functions that I need for example delayMicroseconds() is not available when using Firmata.

Also I saw alot of people trying to get this working using different mode settings for the SRF05 but to be honest I like my code so I want to use that – I use separate echo and trigger pins rather than a singular pin. I reckon this may also help you out should you be having problems getting other values.

Another issue I ran across was converting serial port output to an integer, it just didn’t like this at all so I found a quick solution into fixing this. Although this introduces another error which we have to catch but now I think I have a set of code that works pretty well for what I need.

So first of all take a look at my Arduino SRF05 tutorial.

Arduino SRF05 Sketch

Now you’ve got the circuit and parts use the following sketch on the Arduino board:

const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int index = 0;                  // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int echoPin = 2;             // the SRF05's echo pin
int initPin = 3;             // the SRF05's init pin
unsigned long pulseTime = 0;  // variable for reading the pulse
unsigned long distance = 0;  // variable for storing the distance

void setup() {

  // make the init pin an output:
  pinMode(initPin, OUTPUT);
  // make the echo pin an input:
  pinMode(echoPin, INPUT);
  // initialize the serial port:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
     readings[thisReading] = 0;
  }
  // set the serial port to begin logging values which Processing will later read.
  Serial.begin(9600);
}

void loop() {
  // send the sensor a 10microsecond pulse:
  digitalWrite(initPin, HIGH);
  delayMicroseconds(50);
  digitalWrite(initPin, LOW);

  // wait for the pulse to return. The pulse
  // goes from low to HIGH to low, so we specify
  // that we want a HIGH-going pulse below:

  // converts the microsecond time to distance in CM
  pulseTime = pulseIn(echoPin, HIGH);
  distance = pulseTime/58;

  // subtract the last reading:
  total= total - readings[index];
  // read from the sensor:
  readings[index] = distance;
  // add the reading to the total:
  total= total + readings[index];
  // advance to the next position in the array:
  index = index + 1;                    

  // if we're at the end of the array...
  if (index >= numReadings)  {
    // ...wrap around to the beginning:
    index = 0;
  }
  // calculate the average:
  average = total / numReadings;  

  // print out an A character to set the start of the value and help us
  // cast this value to a string and integer later on in Processing.
  Serial.print('A');

  // now write out our value from the sensor.
  Serial.print(average);
  // delay must be the same as the delay in the processing code
  delay(100);
}

[ad#Google Ad in content]

It’s not too different from the previous tutorial, just gets rid of the LED and the main thing to note is the serial port output at the bottom. We add an A to mark the beginning of the value in the serial output and we use this later on to help cast ou value as a string and then integer, for some reason trying to pass the serial value as an integer or trying to parse it as such fails.

SRF05 Processing Sketch

Now for the Processing code we just need this bit and that’s it – we’re just looking in the log file here to see the values being read correctly. Basically we do a few checks to make sure we have no null values, that the output we’re reading is of expected length and has the correct identifying symbol at the front, you don’t have to use ‘A’, this can actually be anything you want.

// import the serial libary for Processing
import processing.serial.*; 

// define a new port object
Serial port;

// setup the port, this referes to the port object above
// COM8 is my USB port that I use, your's maybe anythign like COM1, etc..
// 9600 is the baud rating (how much data is transferred over a set time)
// it is important to make sure your Arduino is outputting to the same baud rating!!

void setup(){
     port = new Serial(this, "COM8", 9600);
}

// begin our output for Processing
void draw(){

  // delay 100 milliseconds - this must be the same delay used in the Arduino sketch.
  delay(100);

  // create a string to store the value from reading the serial port
  String serialBuffer = port.readString();

  // check if the value is not null, that the value is greater that 2 and no more than 4 characters
  if (serialBuffer != null && serialBuffer.length() >= 2 && serialBuffer.length() <= 4) {

    // check that the first character in the string is A
    // we add A to our output to cast the serial value to a string type.
    // Its also handy as the A is doubled up as a marker for a new value in the serial log
    if (serialBuffer.indexOf("A") == 0) {
      // if this is true then remove A
      serialBuffer =  serialBuffer.substring(1,serialBuffer.length());
    }
    // double check to make sure there are no more A's in our string - otherwise we can't convert to a number
    if (serialBuffer.indexOf("A") == -1) {
      // convert the string to an integer
      int i = Integer.parseInt(serialBuffer);
      // print our integer
      println(i);
    }
  }

}

[ad#Google Ad in content]

Make sure...

Make sure that your serial port is set to the same baud rating in both the Arduino and Processing sketch.

Make sure that the delay used in both executable methods matches.

Make sure that the correct port is being read.

Arduino – making a basic drum machine

arduino piezo

Had a quick look round at turning a piezoelectric speaker in to a sensor that will detect a tap or knock. I also then had a search around for setting the output of a speaker to a different note. Combining this has given me a small basic Arduino drum machine and a headache to my girlfriend.

First of all a piezoelectric speaker works kind of like a guitar string in that it vibrates to generate sound. Typically we pass a current through the 2 pins and this then vibrates the piezo element accordingly, using Pulse Width Modulation allows us to alter the volume and the frequency of the sound wave by altering how frequent we vibrate the piezo material.

So if we reverse this we get a knock sensor which means we vibrate the piezo element by hitting it this then creates a signal that we detect as an input. By sensing the vibrations we can crudely detect how hard it was hit. But because we constantly read the input and the vibrations will reach a peak we need to take the peak value to get a decent result rather than the first or last reading. To do this we write a small chunk of code to take the highest reading.

Next we have a normal speaker as our output, by altering the frequency we can alter the note that it produces, much like creating an Infrared signal in my tutorial here. The frequency is basically created by the microsecond time length of the soundwave and we rapidly pulse the speaker to this length so half the length is on, the other is off. Different notes and octaves have different wave lengths on the chromatic scale. A basic 12 note scale is shown below with the chromatic notes and their frequency along with the timings:

Chromatic Note Frequency Hz Time of soundwave (micro seconds) ?s Pulse On/Off (divide time by 2) ?s
C 261 Hz 3830 ?s 1915 ?s
C# 277 Hz 3610 ?s 1805 ?s
D 294 Hz 3400 ?s 1700 ?s
D# 311 Hz 3216 ?s 1608 ?s
E 329 Hz 3038 ?s 1519 ?s
F 349 Hz 2864 ?s 1432 ?s
F# 370 Hz 2702 ?s 1351 ?s
G 392 Hz 2550 ?s 1275 ?s
G# 415 Hz 2410 ?s 1205 ?s
A 440 Hz 2272 ?s 1136 ?s
A# 466 Hz 2146 ?s 1073 ?s
B 493 Hz 2028 ?s 1014 ?s

To calculate the time of a wave we can use the following calculation:

Time (T) = 1 / frequency (Hz)

This will give us the value in seconds. To obtain microseconds multiply this value by 1,000,000 (There are a million microseconds to 1 second). Conversely we can obtain the frequency by dividing 1 by the Time (in seconds).

I’m going to have 2 piezo speakers as knock sensors which will light up a corresponding LED and play a different note, in this case a C or a D.

Arduino Drum Machine Parts

2x 220 Ohm resistor (Red, Red, Brown, Gold)
2x 1Mega Ohm resistor (Brown, Black, Green, Gold) – that’s 1,000,000 Ohms
2x piezoelectric speakers
1x speaker
2x LED
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
Optional 9V DC power supply or use the USB power for the Arduino

Arduino Piezo Speaker Drum Machine Circuit

Arduino-piezo-drums

Piezo Sensor Drum Machine Code

[ad#Google Ad in content]

/*

LUCKYLARRY.CO.UK - Very basic drum machine/ knock sensors and chromatic scale

We measure the force at which the piezo speakers are hit, the maximum on time is 1024 so when
this is lower than a set threshold we execute our code. In order to take the peak reading we
continously monitor the values and everytime it's lower we save that value. At the end of the loop
we reset the value.

The soundwave function uses a custom monitor for counting microseconds as this seems to be
a bit more accurate for measuring the delays needed. We produce our count by making a value
of microseconds, 35,000, which seems to give a good range of note lengths when multiplied by
how hard the sensor was hit.

We output the sound to another speaker, creating a soundwave based on the Hertz of any given
note in the chromatic scale. Taking this value we calculate the times in microseconds needed
to oscillate and generate the required frequency. Time = (1 / Hz) * 1,000,000.

*/

int leftPadPin = 2;                                             // set the pins for the piezo speakers
int rightPadPin = 5;                                            // these are analog pins for input
int leftLEDPin = 9;                                             // set the LED pins which are digital
int rightLEDPin = 10;
int speakerPin = 6;                                             // set the speaker pin on digital pin 6
int padLimit = 1010;                                            // the limit/ threshold at which to activate the logic
int howHard = 1024;                                             // variable to store how hard the sensor is hit, the lower the value the harder the hit
int  Cnote = 1915;                                              // set the pulse on/off time for each note.
int  Dnote = 1700;  

void setup(){
  pinMode(speakerPin, OUTPUT);                                  // set the speaker as output
  pinMode(leftLEDPin, OUTPUT);                                  // set the LEDs as outputs
  pinMode(rightLEDPin, OUTPUT);
  pinMode(leftPadPin, INPUT);                                   // set the piezo speakers as inputs
  pinMode(rightPadPin, INPUT);
}

void soundwave(int note, int howHard ) {                        // function that takes 2 parameters, the note we want to play and how hard the sensor has been hit
  unsigned long endSoundWave = micros() + (35000 * howHard);    // start a count from the microseconds currently registered since the program first ran. And add on an arbitary value multiplied by howHard value
  while(micros() < endSoundWave){                               // while the count is not reached
    analogWrite(speakerPin, 1023);                              // set the speaker to on/ high
    delayMicroseconds(note);                                    // wait the number of microseconds for the note
    analogWrite(speakerPin, 0);                                 // set the speaker to off/ low
    delayMicroseconds(note);                                    // wait for the same number again to complete our oscillation/ soundwave.
  }                                                             // repeat for the length of time.
}

void loop(){

   if (analogRead(leftPadPin) < padLimit) {                     // if the sensor is hit and the reading is less than our threshold
     digitalWrite(leftLEDPin, HIGH);                            // turn an LED on.
     while (analogRead(leftPadPin) < padLimit) {                // while the analog reading is less than the limit
       if (analogRead(leftPadPin) < howHard) {                  // if the reading valueis less than our howHard value (1024)
         howHard = padLimit - analogRead(leftPadPin);           // then rewrite howHard with the new value
       }                                                        // this allows us to capture the peak value.
       soundwave(Cnote, howHard);                               // now generate the soundwave with our note and how had the sensor was hit
    }
  } 

  if (analogRead(rightPadPin) < padLimit){
     digitalWrite(rightLEDPin, HIGH);
     while (analogRead(rightPadPin) < padLimit) {
       if (analogRead(rightPadPin) < howHard) {
       howHard = padLimit - analogRead(rightPadPin);
       }
       soundwave(Dnote, howHard);
    }
  }

  digitalWrite(rightLEDPin, LOW);
  digitalWrite(leftLEDPin, LOW);                                // set the LED's back to low
  howHard = 1024;                                               // set the variable back to the original value

}

[ad#Google Ad in content]

Well what we could do is to add in extra speakers to allow for chords or alternatively work out the frequency of the chord but then you wouldn't get harmonics and it may sound a bit funny. And perhaps I shouldn't have spent all day playing with this annoying my girlfriend.

Arduino – (Very) Basic motion tracking with 2 PIR sensors

Arduino 2PIR motion tracker

Took me a little while to get started but I’ve managed to wire 2 PIR infrared sensors with an Arduino to sense motion either on the left or on the right side. The result will trigger an LED to represent each PIR sensor then I also added in a servo to be controlled – so it turns left when triggered by the left sensor and so on.

First have a look at my previous tutorial – Arduino PIR motion detector circuit. Now we’re going to use 2 of them and this isn’t that different from just using one of them. However this is only a first attempt so I’ve not calibrated anything properly, for instance we can’t ascertain velocity or true direction of movement because these sensors aren’t that precise and have a wide range of detection. But hey, it’s a start!

Arduino PIR Motion Sensor Circuit Parts

2x 220 Ohm resistor (Red, Red, Brown, Gold)
2x 10K Ohm resistor (Brown, Black, Orange, Gold)
2x PIR sensor
1x Servo (has to need no more than 5v supply)
2x LED
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
Optional 9V DC power supply or use the USB power for the Arduino
You will also need a soldering iron and solder if you use the same PIR as myself.
Some sort of  temporary adhesive to hold the sensors in place.

Arduino Infrared Motion Detector Circuit

So you’ll see that its really just a lot of wires. The PIRs I’ve soldered on the wires and on their output pin there’s a 10K Ohm resistor for each going between them and the positive rail on the breadboard. The LED’s are the same layout as the basic blink tutorials, 220 Ohm resistor between the positive pin (the longer one) and the Arduino pin.

Arduino-2PIR-motion-tracker

PIR Motion Sensor Arduino Code

This isn’t too bad. Basically we set 2 sensors and have a few if statements to do shit based on if they turn on or off, so essentially they’re treated just like a couple of switches.
[ad#Google Ad in content]

/*
LUCKYLARRY.CO.UK - 2 3pin PIR sensors to track basic motion.

We have 1 sensor for left, 1 for right.

The left sensor is triggered, the LED for the left comes on and the servo moves until no motion is detected.
The same happens if the right sensor is triggered.

If both sensors detect motion then its likely the object may be between the 2 but given the field of detection
its not going to be precice. Enjoy!

*/

#include                                                 // Include servo library, you can get it from http://www.arduino.cc/playground/ComponentLib/Servo
Servo myservo;                                                    // Create a servo object
int pos = 0;                                                      // Variable to store the servo position in degrees
int pinPIRleft = 4;                                               // left infrared sensor, digital pin 4
int pinLEDleft = 8;	                                          // left LED, digital pin 8
int pinPIRright = 2;                                              // right sensor, digital pin 2
int pinLEDright = 10;                                             // right LED, digital pin 10

void setup() {
  pinMode(pinLEDleft, OUTPUT);                                    // set LEDs as outputs
  pinMode(pinLEDright, OUTPUT);
  pinMode(pinPIRleft, INPUT);                                     // set sensors as inputs
  pinMode(pinPIRright, INPUT);
  myservo.attach(9);                                              // set the servo to digital pin 9
}

void loop() {

  if (digitalRead(pinPIRleft) == LOW) {                           // if left detects motion
    digitalWrite(pinLEDleft, HIGH);                               // turn on LED
    if ((pos < 180) && (digitalRead(pinPIRright) == HIGH)) {      // if less than 180 degrees and the right sensor is off then move servo
      pos += 1;                                                   // increment servo degrees by +1
      myservo.write(pos);                                         // write the position to the servo
      delay(15);
    }
  } else {
    digitalWrite(pinLEDleft, LOW);                                // otherwise turn off LED and no servo movement
  }

  if (digitalRead(pinPIRright) == LOW) {
    digitalWrite(pinLEDright, HIGH);
    if ((pos >= 1) && (digitalRead(pinPIRleft) == HIGH)) {
      pos -= 1;
      myservo.write(pos);
      delay(15);
    }
  } else {
    digitalWrite(pinLEDright, LOW);
  }

  if ((digitalRead(pinPIRleft) == LOW) && (digitalRead(pinPIRright) == LOW)) {
    // do something here if both sensors detect movement.
  }
}

[ad#Google Ad in content]

And here it is in action:

Well, you could add a 3rd sensor to validate that an object is in front of both sensors, you’ll see that I’ve angled my sensors to try and work this with just 2 sensors. Perhaps limiting the field of detection for each sensor might also be a good thing to make it more precise.