Tuesday, 23 August 2016

Alkaline battery polarity reversal

I was trying to work out what was wrong with a device which wasn't functioning. The first thing I checked was the batteries. When I tested the first battery with the multi-meter it was reading a negative value. I checked my multi-meter leads were connected correctly and tested the battery again. It still read a negative value so I tested the other battery and it was reading the same value only it was positive. These were standard non rechargeable alkaline batteries. I didn't know it was possible to reverse the polarity of a battery let alone a non rechargeable battery so I did some research to find out how its polarity reversed.

The device took 2 batteries and they were connected in series. Additionally as the device had been playing up even though it was not running it had been left with the power switch in the on position. It turns out that if batteries are connected in series and one discharges before the others then a reverse charging current will flow through the discharged battery. This is bad because it can cause the gas pressure inside the battery to rise leading to leakage, deterioration in performance, swelling or rupture. It can also result in the weaker battery becoming reverse charged.

This is why its important not to mix new batteries with old batteries, rechargeable batteries with non rechargeable or even batteries of different brands/model batteries as they could discharge at different rates or have different voltages to begin with.

Reference: Physics Forum

Saturday, 30 January 2016

Powering Arduino projects using batteries

There are a number of ways you can power Arduino projects but if you want to create something which is mobile or is not located near a computer or power point then you have no choice but to use batteries.

Powering Arduino projects using batteries is relatively simple however there are a number of things which should be considered like your budget, required run time, voltage requirements and size/weight restrictions.

What voltage to power the Arduino?
According to the documentation the Arduino can be supplied with 7-12V although 7V is ideal. If run with less than 7V you may experience problems powering outputs and any more than 12V and the regulator can overheat and damage your board. 

Once you have decided what voltage you want to use the easiest way to power the Arduino is using a battery holder with a 2.1mm centre-positive plug which can be connected to the DC input on the Arduino.

Can I use a 9 volt battery? 
You can power the Arduino using a 9V battery but you shouldn't. The voltage regulator on the Arduino is inefficient resulting in large losses. This combined with the fact that 9V batteries have smaller capacities than AA batteries means that you will not be able to power your Arduino as long as with other options. 

I have devices requiring different voltages?
If there are other devices in your project which have different voltage requirements then the simplest solution is to have multiple battery packs. If you decide to use multiple power sources make sure you wire all grounds together or things won't work properly. For example if you have a project where you need to power the Arduino and servos you could have a 7V battery pack connected to the Arduino and a 5V battery pack connected to the Servos (don't forget to wire the grounds together).

Rechargeable versus disposable batteries
There are differences in capacity, terminal voltage and price which should be considered when deciding between disposable and rechargeable.

If you don't already have rechargeable batteries lying around then it is expensive to get started. Rechargeable batteries typically cost around 7 times more than their equivalent non rechargeable equivalent and require charging equipment. These chargers can range in price from quite cheap (mine was bundled with batteries) to expensive (over $100).

The capacity of rechargeable batteries is typically lower than disposables. If you want to get close to the capacity of a disposable alkaline battery you will need to buy the more expensive rechargeable batteries rated around 2300mAh.

An important thing to note if you choose to use rechargeable is that they have a lower terminal voltage of 1.2V versus 1.5V for disposable. This will need to be taken into consideration when choosing a battery holder for the project. For example to power an Arduino using 7V you would require 6 rechargeable batteries compared with 5 if disposables are used.

Hopefully you are now equipped with the knowledge to make an informed decision when deciding how to power your Arduino project using batteries.

Saturday, 21 November 2015

How to recover lost contacts on iPhone

The other day I went to make a call on my iPhone and discovered that all the contacts had disappeared.

It was not the first time it had happened and I only vaguely recalled how I fixed it the first time so I went searching online to find a solution. I found a number forums with people who experienced the same issue but all the fixes I tried didn't bring my contacts back.

Earlier in the day I had unexpectedly been prompted to enter my iCloud details and I clicked cancel so I suspected the issue was related to iCloud contact syncing.

In the end I was able to restore my contact by doing the following:
1. Open Settings->iCloud
Figure 1: iPhone settings menu
2. Click account
Figure 2: iPhone iCloud menu
3. Re-enter your password
Figure 3: iPhone iCloud account settings
4. Click Done

5. Turn off your contact syncing
Figure 4: iPhone iCloud contacts sync option
6. Turn on your contact syncing

7. Finally open your contacts and check if they have come back. If the contacts list is still empty try clicking the refresh icon in the top left of the screen

With any luck after following these steps your contacts will have returned.

Saturday, 15 August 2015

Playing the Spanish Flea tune with an Arduino and a piezo buzzer

I wanted to make the Arduino play a tune so I purchased a piezo buzzer online. I ordered it from AliExpress and it was only a couple dollars including delivery.
Figure 1: Piezo buzzer
Connecting the buzzer to the Arduino is easy. I simply connected the positive wire from the buzzer to a pin which supports Pulse Width Modulation (PWM). On my Arduino Mega 2560 I used pin 3. Then I connected the negative wire from the buzzer to a resistor and the other end of the resistor to ground. I used a 220 ohm resistor. The larger the resistor the quieter the buzzer will sound.
Figure 2: Arduino Mega 2560 and piezo buzzer wiring diagram
Figure 3: Photo of Arduino Mega 2560 and piezo buzzer setup
Playing a tone on the Arduino is done using the Tone function. The official documentation for the tone function can be found here. In my code I used the version of the function which takes three parameters. These are the pin to output the tone on, the frequency of the tone and the duration of the tone. For example if you want to play a frequency of 500Hz on pin 3 for one second you will write code as tone(3, 500, 1000)

I based my code on the example melody code which comes with the Arduino software. The example code contains definitions for each note and the frequency they correspond with. This makes the code much easier to read and debug then if we were to refer to the notes as their frequencies.

As a song is comprised of many notes and the duration of each note is important I created an array for the notes and an array for each notes duration. I called these arrays note and noteDuration. I also created a variable for the beats per minute called bpm to allow me to control the tempo.

Next I setup pin 3 on the Arduino to be an output. In the main loop I call a function called playTune which contains all the code to play the song.

In the playTune function I first calculate the duration of each note. This is done by dividing 60000 (number of milliseconds in a minute) but the number of beats per minute as specified in the bpm variable. After this is calculated I then iterate through the arrays and for each element I call the tone function specifying the note to play and the duration of the note.

As the Tone function is non blocking I then sleep for the duration of the note plus a small delay (I use 10 milliseconds as it sounds better with a small delay) before doing the same with the next array elements. The basic logic of the code is shown in Figure 4 below.

//Plays the tune
void playTune()
  //Determine size of array
  int arraySize = sizeof(note) / sizeof(int);

  //Determine duration of a quarter note
  int quarterNoteDuration = 60000 / bpm;

  //Iterate through note array
  for (int counter = 0; counter < arraySize; counter++)
    if (note[counter] != 0) 
      //Play the note      
      tone(buzzerPin, note[counter], quarterNoteDuration * noteDuration[counter]);

      //Wait for the note to finish before playing next note
      delay(quarterNoteDuration * noteDuration[counter] + 10);
Figure 4: Function to play the tune

I found the trickiest and most time consuming part to be transcribing the song from sheet music into the note and duration arrays.

To begin transcribing the first thing you need is the music. To keep things simple I looked for sheet music which only had a single note being played at any one time. I was able to find several versions of the Spanish Flea song on the MuseScore website including one which satisfied my requirements.

I then went about the arduous task of populating the note and duration arrays. I assigned quarter notes a duration value of 1 as their duration equals one beat. Other notes are assigned a fractional value relative to the duration of a quarter note.

A complete code listing including the populated arrays is in Figure 5 below.

//Playing the Spanish Flea with Arduino and Piezo buzzer 
//Created by Blax

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

int note[] = {
  NOTE_AS5, 0, 0, NOTE_D5, NOTE_DS5, NOTE_E5,
  0, 0, NOTE_G5, NOTE_FS5, NOTE_F5, 
  0, 0, NOTE_F5, NOTE_E5, NOTE_DS5, 
  0, 0, NOTE_G5, NOTE_FS5,NOTE_F5, 
  0, 0, 0, NOTE_F5, NOTE_E5, NOTE_E5, 
  NOTE_DS6, 0, 0, NOTE_DS6, NOTE_F6, NOTE_DS6,
  NOTE_CS6, 0, 0, NOTE_D6, NOTE_DS6, NOTE_D6, 

float noteDuration[] = {
  1, 0.5, 0.5, 1, 0.5, 0.5, 
  1, 0.5, 1, 0.5, 1, 
  1, 0.5, 0.5, 1, 0.5, 0.5, 
  1, 1, 0.5, 0.5, 0.5, 0.5, 
  1, 1, 0.5, 1, 1.5, 
  1, 0.5, 0.5, 0.5, 0.5, 
  1, 1, 0.5, 1, 1.5, 
  1, 0.5, 0.5, 0.5, 0.5, 
  0.5, 0.5, 0.5, 1, 0.5, 1, 
  0.5, 0.5, 0.5, 1, 0.5, 1, 
  1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
  1, 1, 0.5, 1, 1, 
  1, 1, 0.5, 0.5, 0.5, 
  1, 1, 0.5, 1, 1, 
  0.5, 1, 0.5, 0.5, 0.5, 0.5, 
  0.5, 0.5, 0.5, 1, 0.5, 1, 
  0.5, 0.5, 0.5, 1, 0.5, 1, 
  0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
  1, 0.5, 0.5, 1, 0.5, 0.5, 
  1, 0.5, 1, 0.5, 1, 
  1, 0.5, 0.5, 1, 0.5, 0.5, 
  1, 1, 1, 1, 
  1, 1, 0.5, 0.5, 0.5, 0.5, 
  0.5, 1, 1, 0.5, 0.5, 0.5, 
  1, 0.5, 0.5, 0.5, 1, 1.5, 
  0.5, 0.5, 0.5, 0.5, 1, 0.5, 
  1, 1, 0.5, 0.5, 0.5, 0.5, 
  0.5, 1, 1, 0.5, 0.5, 0.5, 
  1, 0.5, 0.5, 0.5, 1, 0.5, 
  0.5, 1, 1

#define buzzerPin 3

#define bpm 160

void setup() 
  pinMode(3, OUTPUT);  

void loop() 

//Plays the tune
void playTune()
  //Determine size of array
  int arraySize = sizeof(note) / sizeof(int);

  //Determine duration of a quarter note
  int quarterNoteDuration = 60000 / bpm;

  //Iterate through note array
  for (int counter = 0; counter < arraySize; counter++)
    if (note[counter] != 0) 
      //Play the note      
      tone(buzzerPin, note[counter], quarterNoteDuration * noteDuration[counter]);

      //Wait for the note to finish before playing next note
      delay(quarterNoteDuration * noteDuration[counter] + 10);
Figure 5: Complete code to play Spanish Flea tune

All that was left was to upload the program to the Arduino and power it up. A video demonstrating the completed project is below.

Figure 6: Video of Arduino playing Spanish Flea tune

Tuesday, 7 July 2015

Testing a 16x2 LCD without a microcontroller

I came across the keypad from an old alarm system and was able to salvage a 16x2 LCD display from it. I was lucky that it was not soldered in place and it was able to easily be removed without damaging it. It also had pins on it which made it perfect for inserting into a breadboard. Photos of the front and back of the salvaged LCD are shown below in Figures 1 and 2.
Figure 1: Front of salvaged 16x2 LCD
Figure 2: Back of salvaged 16x2 LCD

After searching online I found that almost all LCD's use a Hitachi HD44780 or compatible controller. The salvaged LCD looked similar to all other 16x2 LCD's I could find and also had 16 pins so there was a good chance it was the same.

The standard pin out for a LCD is shown below in Figure 3. Additional information can be found in the data sheet here.
Figure 3: Pin out of Hitachi HD44780 compatible LCD
Although it looked like most other LCD's I didn't want to waste time wiring it up to the Arduino and writing a sketch if it wasn't a standard LCD or was broken. After more searching online I found that it is possible to test the LCD using just the LCD and a 5V power supply.

To test the LCD connect the LCD pins as follows:

  1. VSS (pin 1) to GND
  2. VDD (pin 2) to 5V
  3. V0 (pin 3) to GND
  4. LED+ (pin 15) to 5V
  5. LED- (pin 16) to GND 

Figure 4 below shows how to wire the 16x2 LCD for testing. For my testing I used a 5V DC power supply although a battery pack with 4xAA batteries would have worked also.
Figure 4: Wiring diagram of 16x2 LCD test setup
If the display works correctly you should see one blank line and one line filled with blocks as shown in Figure 5 below. If nothing is shown or two lines of blocks appear then the display is not working correctly.
Figure 5: Photo of successful LCD test result
You may notice in the Figure 5 that the positive and negative wires for the LCD back light are the opposite to what is shown in the wiring diagram. During testing I found that my display is not quite standard and the LED pins are reversed. All other pins on the salvaged display are as per the standard.

Wednesday, 17 June 2015

Connecting and programming a HC-SR04 ultrasonic sensor for Arduino

I wanted to make a simple Arduino controlled robot so I ordered a few parts from AliExpress. One of these parts was a HC-SR04 ultrasonic sensor. It is a cheap (a few dollars including delivery) ultrasonic sensor which has sufficient range and accuracy for my needs.

Figure 1: HC-SR04 ultrasonic sensor
The basic details of the HC-SR04 sensor are listed below:
  • Voltage: 5V DC
  • Current: 15mA
  • Minimum range: 2cm
  • Max range: 4m
  • Working frequency: 40Hz
  • Measuring angle: 15 degrees

More details can be found in the data sheet here

The sensor has 4 pins being Vcc, Trig, Echo and GND.

Connecting it to the Arduino is simple. As it has very low power requirements (15mA) the Vcc and GND pins can be directly connected to the 5V and GND pins on the Arduino. The Trig and Echo pins can be connected to any digital IO pins on the Arduino.

A diagram and photo showing how I connected the sensor and Arduino together are shown in Figures 2 and 3 below.
Figure 2: Wiring diagram for Arduino and HC-SR04

Figure 3: Photo of actual Arduino and HC-SR04 setup
Programming the Arduino to work with the sensor is simple but it requires an understanding of how the sensor operates.

The sensor sends out an ultrasonic ping and then measures the time taken for the signal to bounce off the nearest surface and return. It works on all surfaces including glass but can have problems with acoustically soft surfaces like curtains. A diagram illustrating how an ultrasonic sensor works is shown below in Figure 4.

Figure 4: How an ultrasonic sensor works
The ping is initiated when the Trig pin is set high for 10 micro seconds. When the ping returns the Echo pin is held high for the amount of time that the ping took to return.

To convert the ping return time into a distance we need to do some math. The measured time is the round trip time so it includes the time taken for the ping to travel back from the object to the sensor. We only want the distance to the object so we can halve the time.

Now that we know how long sound takes to reach the object we can calculate how far away it is. The speed of sound is approximately 340m/s. There are 100 centimetres in a metre and 1,000,000 microseconds in a second. Therefore it takes sound 1,000,000 / (340 * 100) = 29 microseconds (approximately) to travel 1 centimetre.

So the calculation looks like this:
Distance (cm) = Measured time / 2 / 29

To make the code neater and more reusable I created a function which sends out a ping, measures the return time and returns the result of the calculation (Figure 5 below).
//Returns the distance in centimetres measured by the ultrasonic sensor
int measureDistance()
  //Send an ultrasonic ping
  digitalWrite(SR04TrigPin, HIGH);
  digitalWrite(SR04TrigPin, LOW);
  //Determine the ping time
  long pingTime = pulseIn(SR04EchoPin, HIGH);
  //Calculate the distance
  //Distance to object is only half ping time
  //Takes 29 microseconds to travel 1 cm so divide by 29
  int distance_cm = pingTime / 2 / 29;

  return distance_cm;  
Figure 5: Function which return distance in centimetres

To test the code all that's left is to setup the input and output pins and find a way to display the measured value. I configured pin 3 to be the Trig pin and pin 2 for the echo pin. As for the display I decided to print the result to the serial port as it can be easily viewed in Serial Monitor.

The full code for the project is shown below in Figure 6 and an example output from Serial Monitor is shown in in Figure 7. 

//HC-SR04 ultrasonic sensor test sketch
//Created by Blax

#define SR04TrigPin 3
#define SR04EchoPin 2

void setup() {  
  //Setup HC-SR04 ultrasonic sensor
  pinMode(SR04TrigPin, OUTPUT);
  pinMode(SR04EchoPin, INPUT);
  //Initialize serial communication at 9600bps

void loop() {
  //Get the distance to nearest object
  int distance_cm = measureDistance();
   //Print the distance
  //Wait a half second before measuring again

//Returns the distance in centimetres measured by the ultrasonic sensor
int measureDistance()
  //Send an ultrasonic ping
  digitalWrite(SR04TrigPin, HIGH);
  digitalWrite(SR04TrigPin, LOW);
  //Determine the ping time
  long pingTime = pulseIn(SR04EchoPin, HIGH);
  //Calculate the distance
  //Distance to object is only half ping time
  //Takes 29 microseconds to travel 1 cm so divide by 29
  int distance_cm = pingTime / 2 / 29;

  return distance_cm;  
Figure 6: HC-SR04 ultrasonic sensor test code
Figure 7: Sample code output in Serial Monitor

Wednesday, 3 June 2015

Arduino Mega 2560 clone: Comparison to original and issues downloading sketches using Mac OS X

I recently purchased a clone Arduino mega 2560 from AliExpress. The clone cost less than a quarter of the official unit (including delivery). As such, the decision seemed like a no-brainer. However, I now realise you should not assume the clone will be identical to the original. 

Figure 1: Genuine Arduino Mega 2560

Figure 2: Clone Arduino Mega 2560

My first observation upon opening the package was that the build quality is not as good (refer to Figure 2). Some of the pin headers were quite bent and are shown above after I bent them back into place. This may have occurred during shipping. In addition, the underside of the board is a little untidy.

However, the most surprising observation occurred when I attempted to download a sketch to the Arduino; the connected computer was unable to find it. After reading through a few forums (the most useful forum post was http://forum.arduino.cc/index.php?topic=261375.0) I found that my issue was due to the USB controller on the clone board. 

In addition to differences in general build quality, the clones are also cheaper due to a different USB controller chip; the CH340G as opposed to an ATMega16U2 programmed as a USB-to-Serial converter on the original. If you suspect your board may be the same, you can confirm by checking if you can find a chip with CH340G printed on it (refer to Figure 3). 

Figure 3: CH340G chip on Clone Arduino Mega 2560

After finding this was the issue, the issue was resolved by following the steps outlined below:
  1. Download Mac drivers for CH340G from here (Non English site)
  2. Run the following command in Terminal: sudo nvram boot-args="kext-dev-mode=1”
  3. Restart system
Once installed, I was able to download sketches to the clone without issue.

NOTE: This may not be an issue if you are using an operating system other than Mac OS X (e.g. Microsoft Windows or Linux).