Learn how to use RFID readers with your Arduino. In this instalment we use the Innovations ID-20 RFID reader. The ID-12 and ID-2 are also compatible. If you have the RDM630 or RDM6300 RFID reader, we have a different tutorial.
This is part of a series originally titled “Getting Started with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
Updated 26/02/2013
RFID – radio frequency identification. Some of us have already used these things, and they have become part of everyday life. For example, with electronic vehicle tolling, door access control, public transport fare systems and so on. It sounds complex – but isn’t. In this tutorial we’ll run through the basics of using the ID-20 module then demonstrate a project you can build and expand upon yourself.
Introduction
To explain RFID for the layperson, we can use a key and lock analogy. Instead of the key having a unique pattern, RFID keys hold a series of unique numbers which are read by the lock. It is up to our software (sketch) to determine what happens when the number is read by the lock. The key is the tag, card or other small device we carry around or have in our vehicles. We will be using a passive key, which is an integrated circuit and a small aerial. This uses power from a magnetic field associated with the lock. Here are some key or tag examples:
In this tutorial we’ll be using 125 kHz tags – for example. To continue with the analogy our lock is a small circuit board and a loop aerial. This has the capability to read the data on the IC of our key, and some locks can even write data to keys. And out reader is the Innovations ID-20 RFID reader:
Unlike the RDM630 reader in the other RFID tutorial – the ID-20 is a complete unit with an internal aerial and has much larger reader range of around 160 mm. It’s a 5V device and draws around 65 mA of current. If you have an ID-12 it’s the same except the reader range is around 120mm; and the ID-2 doesn’t have an internal aerial. Connecting your ID-20 reader to the Arduino board may present a small challenge and require a bit of forward planning. The pins on the back of the reader are spaced closer together than expected:
… and for demonstration and prototyping purposes, we’ve soldered on the breakout board with some header pins:
The first thing we’ll do is connect the ID-20 and demonstrate reading RFID tags. First, wire up the hardware as shown below:
If you’re using the breakout board shown earlier, pin 7 matches “+/-” in the diagram above. Next, enter and upload the following sketch (download):
// Example 15a.1
#include <SoftwareSerial.h>
SoftwareSerial id20(3,2); // virtual serial port
char i;
void setup()
{
Serial.begin(9600);
id20.begin(9600);
}
void loop ()
{
if(id20.available()) {
i = id20.read(); // receive character from ID20
Serial.print(i); // send character to serial monitor
Serial.print(" ");
}
}
Note that we’re using a software serial port for our examples. In doing so it leaves the Arduino’s serial lines for uploading sketches and the serial monitor. Now open the serial monitor window, check the speed is set to 9600 bps and wave some tags over the reader – the output will be displayed as below (but with different tag numbers!):
Each tag’s number starts with a byte we don’t need, then twelve that we do, then three we don’t. The last three aren’t printable in the serial monitor. However you do want the twelve characters that appear in the serial monitor. While running this sketch, experiment with the tags and the reader… get an idea for how far away you can read the tags. Did you notice the tag is only read once – even if you leave it near the reader? The ID-20 has more “intelligence” than the RDM630 we used previously. Furthermore when a tag is read, the ID-20 sends a short PWM signal from pin 10 which is just under 5V and lasts for around 230 ms, for example (click image to enlarge):
This signal can drive a piezo buzzer or an LED (with suitable resistor). Adding a buzzer or LED would give a good notification to the user that a card has been read. While you’re reading tags for fun, make a note of the tag numbers for your tags – you’ll need them for the next examples.
RFID Access System
Now that we can read the cards, let’s create a simple control system. It will read a tag, and if it’s in the list of allowed tags the system will do something (light a green LED for a moment). Plus we have another LED which stays on unless an allowed tag is read. Wire up the hardware as shown below (LED1 is red, LED2 is green – click image to enlarge):
Now enter and upload the following sketch (download):
// Example 15a.2
#include
SoftwareSerial id20(3,2); // virtual serial port
// add your tags here. Don't forget to add to decision tree in readTag();
String Sinclair = "4F0023E2129C";
String Smythe = "4F0023CC9737";
String Stephen = "010044523C2B";
String testcard;
char testtag[12];
int indexnumber = 0;
char tagChar;
void setup()
{
Serial.begin(9600);
pinMode(7, OUTPUT); // this if for "rejected" red LED
pinMode(9, OUTPUT); // this will be set high when correct tag is read. Use to switch something on, for now - a green LED.
id20.begin(9600);
digitalWrite(7, LOW);
digitalWrite(9, LOW);
}
void approved()
// when an approved card is read
{
digitalWrite(9, HIGH);
Serial.println("yes");
delay(1000);
digitalWrite(9, LOW);
}
void notApproved()
// when an unlisted card is read
{
digitalWrite(7, HIGH);
Serial.println("no");
delay(100);
digitalWrite(7, LOW);
}
void readTag()
{
tagChar = id20.read();
if (indexnumber != 0) // never a zero in tag number
{
testtag[indexnumber - 1] = tagChar;
}
indexnumber++;
if (indexnumber == 13 ) // end of tag number
{
indexnumber = 0;
testcard = String(testtag);
if (testcard.equals(Sinclair)) {
approved();
}
else if (testcard.equals(Smythe)) {
approved();
}
else if (testcard.equals(Stephen)) {
approved();
}
else {
notApproved();
}
}
}
void loop()
{
readTag();
}
In the function readCard() the sketch reads the tag data from the ID-20, and stores it in an array testtag[]. The index is -1 so the first unwanted tag number isn’t stored in the array. Once thirteen numbers have come through (the one we don’t want plus the twelve we do want) the numbers are smooshed together into a string variable testcard with the function String. Now the testcard string (the tag just read) can be compared against the three pre-stored tags (Sinclair, Smythe and Stephen).
Then it’s simple if… then… else to to see if we have a match, and if so – call the function approved() or disApproved as the case may be. In those two functions you store the actions you want to occur when the correct card is read (for example, control a door strike or let a cookie jar open) or when the system is waiting for another card/a match can’t be found. If you’re curious to see it work, check the following video where we take it for a test run and also show the distances that you have to work with:
Hopefully this short tutorial was of interest. We haven’t explored every minute detail of the reader – but you now have the framework to move forward with your own projects.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Recently a new method of interacting with an ethernet-enabled Arduino board and the Internet was brought to my attention – a new system called Teleduino. In this article we test a few of the basic features and see what is possible. Please note that these are my own experiments and that Teleduino is a work in progress. So follow along and see for yourself.
Getting Started
You will need an Arduino Uno (or compatible) board and Ethernet shield with the Wiznet chip – or a Freetronics EtherTen (a much neater solution). Teleduino now supports Arduino Mega and the awesome EtherMega.
Download and install the Teleduino Arduino library. This is available from the resources section of the home page. You will also need to be running Arduino IDE v1.0 or greater.
Request an API key. This identified your particular Arduino from the rest.
Get together some basic electronics components for testing, such as some LEDs and 560R resistors; sources of analog input such as an LDR or TMP36 temperature sensor; and a solderless breadboard.
Don’t forget the ethernet cable from your Arduino stack to the router!
Finally, some rudimentary knowledge about networking will be useful. (IP address, DHCP, etc.)
The Teleduino system uses pin D8 for a status LED, so you may find connecting one up now useful while experimenting. Connect as such:
Controlling digital outputs
In this example we control an LED, turning it on and off. For demonstration purposes, connect another LED with a resistor to D6 in the same method as shown above. Next, you need to upload a sketch to the Arduino. It is the
TeleduinoEthernetClientProxy.ino
which is included with the library examples. Before uploading, you need to make some modifications. The first of these is to add your API key. Go back to the email you received from Teleduino, and click on the link provided. It will take you to a website that shows a byte array variable named byte key[]. You will copy this into the sketch, replacing the same array full of hexadecimal zeros in the sketch – as shown below – with your own:
… and change one of the hexadecimal numbers to 0×00… just in case there is a clash with other addresses on your network. You never know. Finally – depending on your network router, you may need to manually allocate the IP address for your Ethernet shield and/or set the DNS server to use. To do this, scroll down to
// User configurable variables
where you can change the useDHCP and/or useDNS variables to false, and update those values below. However if you’re not sure, just leave them be unless you need to change them. Finally – upload the sketch to your Arduino, get the hardware together and plug it into the network.
Watch your status LED – it will blink a number of times, depending on the status of things. The blink levels are:
1 blink – initialising
2 blinks – starting network connection
3 blinks – connecting to the Teleduino server
4 blinks – authentication successful
5 blinks – session already exists for supplied key (sometimes happens after a quick restart – will work on next auto-restart)
6 blinks – Invalid or unauthorised key – check your API key is correctly entered in the sketch as described earlier
10 blinks – connection dropped
If all is well, after a minute yours should be on blink level 4, then it will idle back to blink level 1. Now to test the connection with our first command.
You send commands to the Arduino using a set of URLs that will contain various parameters. You will need your API key again for these URLs which is then inserted into the URL. The first will report the version of software on the Arduino. Send
however replace 999999 with your API key (and in all examples shown here). If successful, you should see something similar to the following in the web browser:
However if something is wrong, or there are connection difficulties you will see something like:
Before using digital outputs, and after every reset of the Arduino) you need to set the pin mode for the digital output to control. In our example, we use:
Note that the pin number and mode are set with single digits, as you can see above this is for pin 6, and we use mode=1 for output. You should save this as a bookmark to make life easer later on. When the command has been successfully sent, a message will be shown in the webpage, for example:
Moving forward – you turn the digital output on with the following:
and to turn it off, set the final part of the URL to
output=0
Easy. How did you go? It really is amazing to see it work. Now you can control your Arduino from almost anywhere in the world. Again, saving these as bookmarks to make things easier, or a URL shortening service.
At this point you should now have the gist of the Teleduino service and how it is operated.
There is so much more you can do, and currently the list includes (From the author):
Reset, ping, get version, get uptime, get free memory.
Define pin modes, set digital outputs, set analog outputs, read digital inputs, read analog inputs, or read all inputs with a single API call.
Define up to 2 ‘banks’ of shift registers. Each ‘bank’ can contain up to 32 cascaded shift registers, giving a total of 512 digital outputs.
Shift register outputs can be set, or merged, and expire times can be set on merges (you could set an output(s) high for X number of milliseconds).
Define, and read and write from serial port.
Read and write from EEPROM.
Define and position up to 6 servos.
Set preset values for the above functions, which get set during boot. Preset values are stored in the first 160ish bytes of the EEPROM.
For more information check the Teleduino web site, and further tutorials can be found here. Here is a simple example of Teleduino at work – controlling a light switch:
Conclusion
At this moment Teleduino is simple, works and makes a lot of ideas possible. We look forward to making more use of it in future projects, and hope you can as well. Kudos to Nathan Kennedy, and we look forward to seeing Teleduino advance and develop over the future. If all this Arduino is new to you, check out the tutorials. Thanks to Freetronics for the use of their Ethernet-enabled hardware.
In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
In this article we discuss how to use the Microchip MCP23017 16-bit serial expander with I2C serial interface. This 28-pin IC offers sixteen inputs or outputs – and up to eight of the ICs can be used on one I2C bus… offering a maximum of 128 extra I/O ports. A few people may be thinking “Why not just get an Arduino Mega2560?” – a good question. However you may have a distance between the Arduino and the end-point of the I/O pins – so with these ICs you can run just four wires instead of a lot more; save board space with custom designs, and preserve precious digital I/O pins for other uses. Plus I think the I2C bus is underappreciated! So let’s get started…
Here is our subject of the article in DIP form:
At this point you should also download yourself a copy of data sheet – it will be referred to several times, and very useful for reference and further reading. Furthermore if you are not familiar with Arduino and the I2C bus, please familiarise yourself with the I2C tutorials parts one and two. The MCP23017 can be quite simple or complex to understand, so the goal of this article is to try and make it as simple as possible. After reading this you should have the knowledge and confidence to move forward with using a MCP23017.
First, let’s look at the hardware basics of this IC. Consider the pinouts:
The sixteen I/O ports are separated into two ‘banks’ – A (on the right) and B (on the left. Pin 9 connects to 5V, 10 to GND, 11 isn’t used, 12 is the I2C bus clock line (Arduino Uno/Duemilanove analogue pin 5, Mega pin 21), and 13 is the I2C bus data line (Arduino Uno/Duemailnove analogue pin 4, Mega pin 20). External pull-up resistors should be used on the I2C bus – in our examples we use 4.7k ohm values. Pin 14 is unused, and we won’t be looking at interrupts, so ignore pins 19 and 20. Pin 18 is the reset pin, which is normally high – therefore you ground it to reset the IC. So connect it to 5V!
Finally we have the three hardware address pins 15~17. These are used to determine the I2C bus address for the chip. If you connect them all to GND, the address is 0×20. If you have other devices with that address or need to use multiple MCP23017s, see figure 1-2 on page eight of the data sheet. You can alter the address by connecting a combination of pins 15~17 to 5V (1) or GND (0). For example, if you connect 15~17 all to 5V, the control byte becomes 0100111 in binary, or 0×27 in hexadecimal.
Next, here is a basic schematic illustrating how to connect an MCP23017 to a typical Arduino board. It contains the minimum to use the IC, without any sensors or components on the I/O pins:
Now to examine how to use the IC in our sketches.
As you should know by now most I2C devices have several registers that can be addressed. Each address holds one byte of data that determines various options. So before using we need to set whether each bank is an input or an output. First, we’ll examine setting them as outputs. So to set bank A to outputs, we use:
Wire.beginTransmission(0x20);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // set all of bank A to outputs
Wire.endTransmission();
Then to set bank B to outputs, we use:
Wire.beginTransmission(0x20);
Wire.write(0x01); // IODIRB register
Wire.write(0x00); // set all of bank B to outputs
Wire.endTransmission();
So now we are in void loop() or a function of your own creation and want to control some output pins.
To control bank A, we use:
Wire.beginTransmission(0x20);
Wire.write(0x12); // address bank A
Wire.write(??); // value to send
Wire.endTransmission();
To control bank B, we use:
Wire.beginTransmission(0x20);
Wire.write(0x13); // address bank B
Wire.write(??); // value to send
Wire.endTransmission();
… replacing ?? with the binary or equivalent hexadecimal or decimal value to send to the register.
To calculate the required number, consider each I/O pin from 7 to 0 matches one bit of a binary number – 1 for on, 0 for off. So you can insert a binary number representing the status of each output pin. Or if binary does your head in, convert it to hexadecimal. Or a decimal number. So for example, you want pins 7 and 1 on. In binary that would be 10000010, in hexadecimal that is 0×82, or 130 decimal. (Using decimals is convenient if you want to display values from an incrementing value or function result).
If you had some LEDs via resistors connected to the outputs, you would have this as a result of sending 0×82:
For example, we want bank A to be 11001100 and bank B to be 10001000 – so we send the following (note we converted the binary values to decimal):
Wire.beginTransmission(0x20);
Wire.write(0x12); // address bank A
Wire.write(204); // value to send
Wire.endTransmission();
Wire.beginTransmission(0x20);
Wire.write(0x13); // address bank B
Wire.write(136); // value to send
Wire.endTransmission();
… with the results as such (bank B on the left, bank A on the right):
Now let’s put all of this output knowledge into a more detailed example. From a hardware perspective we are using a circuit as described above, with the addition of a 560 ohm resistor followed by an LED thence to ground from on each of the sixteen outputs. Here is the sketch (download):
Example 41.1
/*
Example 41.1 - Microchip MCP23017 with Arduino
http://tronixstuff.wordpress.com/tutorials > chapter 41
John Boxall | CC by-sa-nc
*/
// pins 15~17 to GND, I2C bus address is 0x20
#include "Wire.h"
void setup()
{
Wire.begin(); // wake up I2C bus
// set I/O pins to outputs
Wire.beginTransmission(0x20);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // set all of bank A to outputs
Wire.endTransmission();
Wire.beginTransmission(0x20);
Wire.write(0x01); // IODIRB register
Wire.write(0x00); // set all of bank B to outputs
Wire.endTransmission();
}
void binaryCount()
{
for (byte a=0; a<256; a++)
{
Wire.beginTransmission(0x20);
Wire.write(0x12); // GPIOA
Wire.write(a); // bank A
Wire.endTransmission();
Wire.beginTransmission(0x20);
Wire.write(0x13); // GPIOA
Wire.write(a); // bank B
Wire.endTransmission();
}
}
void loop()
{
binaryCount();
delay(500);
}
And here is the example blinking away:
Although that may have seemed like a simple demonstration, it was created show how the outputs can be used. So now you know how to control the I/O pins set as outputs. Note that you can’t source more than 25 mA of current from each pin, so if switching higher current loads use a transistor and an external power supply and so on.
Now let’s turn the tables and work on using the I/O pins as digital inputs. The MCP23017 I/O pins default to input mode, so we just need to initiate the I2C bus. Then in the void loop() or other function all we do is set the address of the register to read and receive one byte of data.
For our next example, we have our basic sketch as described at the start of this article using four normally-open buttons (once again using the ‘button board‘) which are connected to bank B inputs 0~3. Consider the first five lines of void loop() in the following example (download);
Example 41.2
/*
Example 41.2 - Microchip MCP23017 with Arduino
http://tronixstuff.wordpress.com/tutorials > chapter 41
John Boxall | CC by-sa-nc
*/
// pins 15~17 to GND, I2C bus address is 0x20
#include "Wire.h"
byte inputs=0;
void setup()
{
Serial.begin(9600);
Wire.begin(); // wake up I2C bus
}
void loop()
{
Wire.beginTransmission(0x20);
Wire.write(0x13); // set MCP23017 memory pointer to GPIOB address
Wire.endTransmission();
Wire.requestFrom(0x20, 1); // request one byte of data from MCP20317
inputs=Wire.read(); // store the incoming byte into "inputs"
if (inputs>0) // if a button was pressed
{
Serial.println(inputs, BIN); // display the contents of the GPIOB register in binary
delay(200); // for debounce
}
}
In this example void loop() sends the GPIOB address (0×13) to the IC. Then using Wire.requestFrom() it asks for one byte of data from the IC – the contents of the register at 0×13. This byte is stored in the variable inputs. Finally if inputs is greater than zero (i.e. a button has been pressed) the result is sent to the serial monitor window and displayed in binary. We display it in binary as this represents the state of the inputs 0~7. Here is an example of pressing the buttons 1, 2, 3 then 4 – three times:
And as we are reading eight inputs at once – you can detect multiple keypresses. The following is an example of doing just that:
As you can see pressing all four buttons returned 1111, or the first and third returned 101. Each combination of highs and lows on the inputs is a unique 8-bit number that can also be interpreted in decimal or hexadecimal. And if you wanted to read all sixteen inputs at once, just request and store two bytes of data instead of one.
For our last example – a demonstration of using bank A as outputs and bank B as inputs. Four LEDs with matching resistors are connected to bank A outputs 0~3, with the buttons connected as per example 41.2. Here is the sketch (download):
Example 41.3
/*
Example 41.2 - Microchip MCP23017 with Arduino
http://tronixstuff.wordpress.com/tutorials > chapter 41
John Boxall | CC by-sa-nc
*/
// pins 15~17 to GND, I2C bus address is 0x20
#include "Wire.h"
byte inputs=0;
void setup()
{
Serial.begin(9600);
Wire.begin(); // wake up I2C bus
}
void loop()
{
Wire.beginTransmission(0x20);
Wire.write(0x13); // set MCP23017 memory pointer to GPIOB address
Wire.endTransmission();
Wire.requestFrom(0x20, 1); // request one byte of data from MCP20317
inputs=Wire.read(); // store the incoming byte into "inputs"
if (inputs>0) // if a button was pressed
{
Serial.println(inputs, BIN); // display the contents of the GPIOB register in binary
delay(200); // for debounce
}
}
By now there shouldn’t be any surprises in the last example – it receives a byte that represents bank B, and sends that byte out to bank A to turn on the matching outputs and LEDs. For the curious, here it is in action:
So there you have it… another way to massively increase the quantity of digital I/O pins on any Arduino system by using the I2C bus.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
[Update: 21/05/2013. Tutorial now out of date, and I don't have a Nano to test it with the new code. Try this instead.]
In this article we will introduce playing MP3 files using the Gravitech Arduino Nano and MP3 add-on board as shown earlier. This board utilises the VLSI VS1053B decoder IC, which is quite well specified (download the data sheet [.pdf]). However in the interests of keeping things simple we will look at the most popular use – playback of MP3 files. The MP3 files can be in stereo, see the data sheet for more information with regards to bit rate etc. Here again is our board, both top:
… and bottom:
Using this board we can initiate playback to a pair of earphones, or an external amplifier. There is also a tiny speaker connected to the left audio channel, however it is not made for loud broadcasting. However if you place a piece of tape over it you can increase the volume and bass response Some of you may be thinking “oh wow!, let’s make our own MP3 player” – which is a pretty normal thought after seeing this shield for the first time. However due to the size of the system, portability may be an issue. However, after some thought there are many uses for the shield, such as:
Event-driven recording playback. For example, you could standardise PA announcements by playing back pre-recorded messages at the press of a button instead of attempting to train staff to articulate themselves in an understandable manner (e.g. railway annoucements);
Modification of devices for the vision-impaired – a recording could be played after a particular event has occurred with the device;
Adding voice or music output to an art installation;
Etcetera
You get the idea. From a hardware perspective, you will need the Arduino Nano, the MP3 add-on board, and a microSD card. It is recommended that you not use a microSDHC card as they can be somewhat unreliable in this situation. Furthermore, please format the card with the FAT16 or FAT32 file system. Finally, to prepare for our first example – please copy the MP3 files downloadable from here onto your microSD card.
Now some preliminary software work needs to be done. Please download and install the SdFat library. The VLSI 1053B decoder chip uses the SPI bus (SPI? See my tutorials, parts one and two) – and so does the microSD card. Generally the CS (chip select) line is connected to digital 10 on Arduino – but our MP3 board uses 4. So we need to slightly modify the SdFat library to take this into account. Let’s do this now. First of all, locate and open in a text editor the file Sd2PinMap.h. It will be located in the library folder as shown below:
Now, scroll down to line number 279 in the file, and change the parameter uint8_t const SS_PIN from 10 to 4 – as such:
Finally, save and close the file. If you are working with other products that use the SPI bus and an SD card reader, you may want to run two separate Arduino IDE/library installations. At this point ensure your microSD card is formatted, contains the initial demonstration MP3 files, and inserted into the card socket underneath the board. Finally – insert your Nano into the MP3 board, plug in some headphones (or move the volume knob to mid-postion) and the USB lead. Then download and install this demonstration sketch. You can ignore the message in the sketch about changing the SS pin as we have done this in the library. You will hear some bells (track001.mp3) and drums (track002.mp3).
A brief look at that sketch reveals much code that to the beginner or intermediate user could be somewhat confusing. But don’t let this worry you, we can rearrange a few things to make using the MP3 shield very easy. For our next example, we will learn how to alter the headphone output volume, and select which track to play. Download and open this sketch, and also download and copy these example sound files to your microSD card.
You can ignore everything except for the void loop() section of the sketch – there are two functions of note. The first being:
Mp3SetVolume(0,0);
This sets the output volume for the left and right audio channel. 0 is maximum volume, and the minimum is over 250. You should call this function every time if you need a default volume lower than 100% after every system reset/power cycle. The other function to note is:
playMP3("news.mp3");
This function is the goal of the exercise – just insert the file name of the MP3 you want to play. Note that file names must be in the old 8.3 character format (e.g. “evie123.mp3″ and not “Evie – Parts 1, 2 and 3.mp3″). Now you can have your sketch fire up the MP3 player on request – you can insert your code into this sketch and modify as required.
At this point you may be considering the output options of the MP3 board apart from a pair of earphones. Things are not entirely as they seem, and some thought does need to go into the hardware connections. Do not connect anything else apart from normal stereo “walkman”-style earphones to the socket on the board. Doing so will risk damaging the decoder IC. Furthermore, if you wish to connect the output from the board to an external amplifier, some extra circuitry is required. Some of this is included on the board, and some is not. First, please download and view the VS1053 output guide (.pdf). Turn to page eight to find the following schematic:
In order to connect to a line-out input of an amplifier via the earphone socket, you will need to recreate the circuit above. Some of this has been done on the board – resistors R7~R9 and C3~C5 are preinstalled. You can see this in the MP3 shield schematic. So do the right thing and reap the rewards!
Now you can go forth and musify your creations with MP3 music and other recordings. Please note that this article would not have been possible without the example Arduino sketches provided by Nathan Seidle, the founder and CEO of Sparkfun. If you meet him, buy him a beer.
If you have any further hardware questions or enquiries relating to the Arduino Nano or MP3 board, please direct them to Gravitech via their contact page. The Gravitech Arduino Nano and MP3 board used in this article were promotional considerations provided by Gravitech, whose products including the Arduino Nanofamily are available directly from their website or these distributors.
As always, thank you for reading and I look forward to your comments and so on. Furthermore, don’t be shy in pointing out errors or places that could use improvement. Please subscribe using one of the methods at the top-right of this web page to receive updates on new posts, follow on twitter, facebook, or join our Google Group.
Otherwise, have fun, be good to each other – and make something!
In this article we will examine yet another product from a bundle sent for review by Snootlab, a Toulouse, France-based company that in their own words:
… designs and develops electronic products with an Open Hardware and Open Source approach. We are particularly specialized in the design of new shields for Arduino. The products we create are licensed under CC BY-SA v3.0 (as shown in documents associated with each of our creations). In accordance with the principles of the definition of Open Source Hardware (OSHW), we have signed it the 10th February 2011. We wish to contribute to the development of the ecosystem of “do it yourself” through original designs of products, uses and events.
Furthermore, all of their products are RoHS compliant and as part of the Open Hardware commitment, all the design files are available from the Snootlab website.
The subject of the review is the Snootlab Rotoshield – a motor-driver shield for our Arduino systems. Using a pair of L293 half-bridge motor driver ICs, you can control four DC motors with 256 levels of speed, or two stepper motors. However this is more than just a simple motor-driver shield… The PCB has four bi-colour LEDs, used to indicate the direction of each DC motor; there is a MAX7313 IC which offers another eight PWM output lines; and the board can accept external power up to 18V, or (like other Snootlab shields) draw power from a PC ATX power supply line.
However as this is a kit, let’s follow construction, then explore how the shield could possibly be used. [You can also purchase the shield fully assembled - but what fun would that be?] Assembly was relatively easy, and you can download instructions and the schematic files in English. As always, the kit arrives in a reusable ESD bag:
There are some SMD components, and thankfully they are pre-soldered to the board. These include the SMD LEDs, some random passives and the MAX7313:
Thankfully the silk-screen is well noted with component numbers and so on:
All the required parts are included, including stackable headers and IC sockets:
It is nice to not see any of the old-style ceramic capacitors. The people at Snootlab share my enthusiasm for quality components. The assembly process is pretty simple, just start with the smaller parts such as capacitors:
… then work outwards with the sockets and terminals:
… then continue on with the larger, bulkier components. My favourite flexible hand was used to hold the electrolytics in place:
… followed with the rest, leaving us with one Rotoshield:
If you want to use the 12V power line from the ATX socket, don’t forget to bridge the PCB pads between R7 and the AREF pin. The next thing to do is download and install the snooter library to allow control of the Rotoshield in your sketches. There are many examples included with the library that you can examine, just select File > Examples > snootor in the Arduino IDE to select an example. Function definitions are available in the readme.txt file included in the library download.
[Update]
After acquiring a tank chassis with two DC motors, it was time to fire up the Rotoshield and get it to work. From a hardware perspective is was quite simple – the two motors were connected to the M1 and M2 terminal blocks, and a 6V battery pack to the external power terminal block on the shield. The Arduino underneath is powered by a separate PP3 9V battery.
In the following sketch I have created four functions – goForward(), goBackward(), rotateLeft() and rotateRight(). The parameter is the amount of time in milliseconds to operate for. The speed of the motore is set using the Mx.setSpeed() function in void Setup(). Although the speed range is from zero to 255, this is PWM so the motors don’t respond that well until around 128. So have just set them to full speed. Here is the demonstration sketch:
For support, visit the Snootlab website and customer forum in French (use Google Translate). However as noted previously the team at Snootlab converse in excellent English and have been easy to contact via email if you have any questions. Snootlab products including the Snootlab Rotoshieldare available directly from their website. High-resolution images available on flickr.
As always, thank you for reading and I look forward to your comments and so on. Furthermore, don’t be shy in pointing out errors or places that could use improvement. Please subscribe using one of the methods at the top-right of this web page to receive updates on new posts, follow on twitter, facebook, or join our Google Group.
[Disclaimer - the products reviewed in this article are promotional considerations made available by Snootlab]
Otherwise, have fun, be good to each other – and make something!
Learn how to control AC outlets via SMS text message. This is chapter thirty-three of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
In this chapter we will continue with the use of the SM5100 cellular shield to turn digital outputs on and off via SMS. However please read chapters twenty-six and twenty-seven first if you are unfamiliar with using the GSM shield with Arduino. As an extension of chapter twenty-seven, we will use our Arduino to turn on or off AC outlets via a common remote-control AC outlet pack. Please note this is more of a commentary of my own experience, and not an exact tutorial. In other words, by reading this I hope you will gain some ideas into doing the necessary modifications yourself and in your own way.
Firstly, we need some remote-control AC outlets. Most electrical stores or giant retail warehouses may have something like this:
Nothing too original, just a wireless remote control that can switch on or off receiver outlets on a choice of four radio frequencies. Before moving forward I would like to acknowledge that this article was inspired by the wonderful book Practical Arduino – Cool Projects for Open Source Hardware by Jon Oxer and Hugh Blemings. In chapter two an appliance remote-control system is devised using a similar system.
At first glance the theory behind this project is quite simple – using the hardware in example 27.2, instead of controlling LEDs, activate the buttons on the wireless remote control for the AC outlets – leaving us with AC outlets controlled via SMS. However there are a few things to keep in mind and as discovered during the process, various pitfalls as well.
Before voiding the warranty on your remote control, it would be wise to test the range of the remote control to ensure it will actually work in your situation. I found this was made a lot easier by connecting a radio to the remote outlet – then you can hear when the outlet is on or off. If this is successful, make a note of the amount of time required to press the on and off buttons – as we need to control the delay in our Arduino sketch.
The next step is to crack open the remote control:
… and see what we have to work with:
Straight away there are two very annoying things – the first being the required power supply – 12 volts; and the second being the type of button contacts on the PCB. As you can see above we only have some minute PCB tracks to solder our wires to. It would be infinitely preferable to have a remote control that uses actual buttons soldered into a PCB, as you can easily desolder and replace them with wires to our Arduino system. However unless you can casually tear open the remote control packaging in the store before purchase, it can be difficult to determine the type of buttons in the remote.
As you can see in the photo above, there is an off and on pad/button each for four channels of receiver. In my example we will only use two of them to save time and space. The next question to solve is how to interface the Arduino digital outputs with the remote control. In Practical Arduino, the authors have used relays, but I don’t have any of those in stock. However I do have a quantity of common 4N25 optocouplers, so will use those instead. An optocoupler can be thought of as an electronic switch that is isolated from what is it controlling – see my article on optocouplers for more information.
Four optocouplers will be required, two for each radio channel. To mount them and the associated circuitry, we will use a blank protoshield and build the Arduino-remote control interface onto the shield. The circuitry for the optocoupler for each switch is very simple, we just need four of the following:
As the LED inside the optocoupler has a forward voltage of 1.2 volts at 10mA, the 390 ohm resistor is required as our Arduino digital out is 5 volts. Dout is connected to the particular digital out pin from the Arduino board. Pins 4 and 5 on the optocoupler are connected to each side of the button contact on our remote control.
The next consideration is the power supply. The remote control theoretically needs 12 volts, however the included battery only measured just over nine. However for the optimum range, the full 12 should be supplied. To save worrying about the battery, our example will provide 12V to the remote control. Furthermore, we also need to supply 5 volts at a higher current rating that can be supplied by our Arduino. In the previous GSM chapters, I have emphasised that the GSM shield can possibly draw up to two amps in current. So once again, please ensure your power supply can deliver the required amount of current. From experience in my location, I know that the GSM shield draws around 400~600 milliamps of current – which makes things smaller and less complex.
The project will be supplied 12 volts via a small TO-92 style 78L12 regulator, and 5 volts via a standard TO-220 style 7805 regulator. You could always use a 7812, the 78L12 was used as the current demand is lower and the casing is smaller. The power for the whole project will come from a 15V DC 1.5A power supply. So our project’s power supply schematic will be as follows:
Now to mount the optocouplers and the power circuitry on the blank protoshield. Like most things in life it helps to make a plan before moving forward. I like to use graph paper, each square representing a hole on the protoshield, to plan the component layout. For example:
It isn’t much, but it can really help. Don’t use mine – create your own, doing so is good practice. After checking the plan over, it is a simple task to get the shield together. Here is my prototype example:
It isn’t neat, but it works. The header pins are used to make connecting the wires a little easier, and the pins on the right hand side are used to import the 15V and export 12V for the remote.
While the soldering iron is hot, the wires need to be soldered to the remote control. Due to the unfortunate size of the PCB tracks, there wasn’t much space to work with:
But with time and patience, the wiring was attached:
Again, as this is a prototype the aesthetics of the modification are not that relevant. Be careful when handling the remote, as any force on the wiring can force the soldered wire up and break the PCB track. After soldering each pair of wires to the button pads, use the continuity function of a multimeter to check for shorts and adjust your work if necessary.
At this stage the AC remote control shield prototype is complete. It can be tested with a simple sketch to turn on and off the related digital outputs. For example, the following sketch will turn on and off each outlet in sequence:
void setup()
{
pinMode(9, OUTPUT); // 1 off
pinMode(8, OUTPUT); // 1 on
pinMode(5, OUTPUT); // 2 off
pinMode(4, OUTPUT); // 2 on
}
void loop()
{
// outlets on channel 1 on
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(5000);
// outlets on channel 1 off
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(5000);
// outlets on channel 2 on
digitalWrite(4, HIGH);
delay(1000);
digitalWrite(4, LOW);
delay(5000);
// outlets on channel 2 off
digitalWrite(5, HIGH);
delay(1000);
digitalWrite(5, LOW);
delay(5000);
}
Now to get connected with our GSM shield. It is a simple task to insert the remote shield over the GSM shield combination, and to connect the appropriate power supply and (for example) GSM aerial. The control sketch is a slight modification of example 27.2, and is shown below:
int aon = 8;
int aoff = 9;
int bon = 4;
int boff = 5;
int pressdelay = 1000; // duration to activate a button on remote
void setup()
{
// prepare the digital output pins
pinMode(aon, OUTPUT);
pinMode(aoff, OUTPUT);
pinMode(bon, OUTPUT);
pinMode(boff, OUTPUT);
//Initialize GSM module serial port for communication.
cell.begin(9600);
delay(30000); // give time for GSM module to register on network etc.
cell.println("AT+CMGF=1"); // set SMS mode to text
delay(200);
cell.println("AT+CNMI=3,3,0,0"); // set module to send SMS data to serial out upon receipt
delay(200);
}
void loop()
{
//If a character comes in from the cellular module...
if(cell.available() >0)
{
inchar=cell.read();
if (inchar=='#')
{
delay(10);
inchar=cell.read();
if (inchar=='a')
{
delay(10);
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(aoff, HIGH);
delay(pressdelay);
digitalWrite(aoff, LOW);
}
else if (inchar=='1')
{
digitalWrite(aon, HIGH);
delay(pressdelay);
digitalWrite(aon, LOW);
}
delay(10);
inchar=cell.read();
if (inchar=='b')
{
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(boff, HIGH);
delay(pressdelay);
digitalWrite(boff, LOW);
}
else if (inchar=='1')
{
digitalWrite(bon, HIGH);
delay(pressdelay);
digitalWrite(bon, LOW);
The variable pressdelay stores the amount of time in milliseconds to ‘press’ a remote control button. To control our outlets, we send a text message using the following syntax:
#axbx
Where a/b are remote channels one and two, and x is replaced with 0 for off and 1 for on.
So there you have it – controlling almost any AC powered device via text message from a cellular phone. Imagine trying to do that ten, or even five years ago. As always, now it is up to you and your imagination to find something to control or get up to other shenanigans.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Learn how to use Arduino and infra-red remote controls in chapter thirty-two of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
Updated 05/02/2013
In this article we will look at something different to the usual, and hopefully very interesting and useful – interfacing our Arduino systems with infra-red receivers. Why would we want to do this? To have another method to control our Ardiuno-based systems, using simple infra-red remote controls.
A goal of this article is to make things as easy as possible, so we will not look into the base detail of how things work - instead we will examine how to get things done. If you would like a full explanation of infra-red, perhaps see the page on Wikipedia. The remote controls you use for televisions and so on transmit infra-red beam which is turned on and off at a very high speed – usually 38 kHz, to create bits of serial data which are then interpreted by the receiving unit. As the wavelength of infra-red light is too high for human eyes, we cannot see it. However using a digital camera – we can. Here is a demonstration video of IR codes being sent via a particularly fun kit – the adafruit TV-B-Gone:
Now to get started. You will need a remote control, and a matching IR receiver device. The hardware and library used in this tutorial only supports NEC, Sony SIRC, Philips RC5, Philips RC6, and raw IR protocols. Or you can purchase a matching set for a good price, such as this example:
Or you may already have a spare remote laying around somewhere. I kept this example from my old Sony Trinitron CRT TV after it passed away:
It will more than suffice for a test remote. Now for a receiver – if you have purchased the remote/receiver set, you have a nice unit that is ready to be wired into your Arduino, and also a great remote that is compact and easy to carry about. To connect your receiver module – as per the PCB labels, connect Vcc to Arduino 5V, GND to Arduino GND, and D (the data line) to Arduino digital pin 11.
Our examples use pin 11, however you can alter that later on. If you are using your own remote control, you will just need a receiver module. These are very cheap, and an ideal unit is the Vishay TSOP4138 (data sheet .pdf). These are available from element-14 and the other usual retail suspects. They are also dead-simple to use. Looking at the following example:
From left to right the pins are data, GND and Vcc (to Arduino +5V). So it can be easily wired into a small breadboard for testing purposes. Once you have your remote and receiver module connected, you need to take care of the software side of things. There is a new library to download and install, download it from here. Extract the IRremote folder and place into the ..\arduino-002x\libraries folder. Then restart your Arduino IDE if it was already open.
Using Arduino v1.0? Open the file “IRRemoteInt.h” in the library folder, and change the line
#include <WProgram.h>
to
#include <Arduino.h>
Then save and close the file, restart the Arduino IDE and you’re set.
With our first example, we will receive the commands from our remote control and display them on the serial monitor. Download and run the following sketch:
// example 32.1 - IR receiver code repeater
// http://tronixstuff.com/tutorials > chapter 32
// based on code by Ken Shirriff - http://arcfn.com
#include <IRremote.h> // use the library
int receiver = 11; // pin 1 of IR receiver to Arduino digital pin 11
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results;
void setup()
{
Serial.begin(9600); // for serial monitor output
irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
if (irrecv.decode(&results)) // have we received an IR signal?
{
Serial.println(results.value, HEX); // display it on serial monitor in hexadecimal
irrecv.resume(); // receive the next value
} // Your loop can do other things while waiting for an IR command
}
Open the serial monitor box, point your remote control to the receiver and start pressing away. You should see something like this:
What have we here? Lots of hexadecimal numbers. Did you notice that each button on your remote control resulted in an individual hexadecimal number? I hope so. The number FFFFFFFF means that the button was held down. The remote used was from a yum-cha discount TV. Now I will try again with the Sony remote:
This time, each button press resulted in the same code three times. This is peculiar to Sony IR systems. However nothing to worry about. Looking back at the sketch for example 32.1, the
if (irrecv.decode(&results))
section is critical – if a code has been received, the code within the if statement is executed. The hexadecimal code is stored in the variable
results.value
with which we can treat as any normal hexadecimal number. At this point, press a few buttons on your remote control, and take a note of the matching hexadecimal codes that relate to each button. We will need these codes for the next example…
Now we know how to convert the infra-red magic into numbers, we can create sketches to have our Arduino act on particular commands. As the IR library returns hexadecimal numbers, we can use simple decision functions to take action. In the following example, we use switch…case to examine each inbound code, then execute a function. In this case we have an LCD module connected via I2C, and the sketch is programmed to understand fifteen Sony IR codes. If you don’t have an LCD you could always send the output to the serial monitor. If you are using the DFRobot I2C LCD display, you need to use Arduino v23.
Furthermore you can substitute your own values if not using Sony remote controls. Finally, this sketch has a short loop after the translateIR(); function call which ignores the following two codes – we do this as Sony remotes send the same code three times. Again. you can remove this if necessary. Note that when using hexadecimal numbers in our sketch we preced them with 0x.
// for Sony IR codes (ignores 2nd and 3rd signal repeat)
// http://tronixstuff.com/tutorials > chapter 32
// based on code by Ken Shirriff - http://arcfn.com
#include "Wire.h" // for I2C bus
#include "LiquidCrystal_I2C.h" // for I2C bus LCD module http://bit.ly/eNf7jM
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
#include <IRremote.h> // use the library for IR
int receiver = 11; // pin 1 of IR receiver to Arduino digital pin 11
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results;
void setup()
{
lcd.init(); // initialize the lcd
lcd.backlight(); // turn on LCD backlight
irrecv.enableIRIn(); // Start the receiver
}
void translateIR() // takes action based on IR code received
// describing Sony IR codes on LCD module
{
switch(results.value)
{
case 0x37EE: lcd.println(" Favourite "); break;
case 0xA90: lcd.println(" Power button "); break;
case 0x290: lcd.println(" mute "); break;
case 0x10: lcd.println(" one "); break;
case 0x810: lcd.println(" two "); break;
case 0x410: lcd.println(" three "); break;
case 0xC10: lcd.println(" four "); break;
case 0x210: lcd.println(" five "); break;
case 0xA10: lcd.println(" six "); break;
case 0x610: lcd.println(" seven "); break;
case 0xE10: lcd.println(" eight "); break;
case 0x110: lcd.println(" nine "); break;
case 0x910: lcd.println(" zero "); break;
case 0x490: lcd.println(" volume up "); break;
case 0xC90: lcd.println(" volume down "); break;
case 0x90: lcd.println(" channel up "); break;
case 0x890: lcd.println(" channel down "); break;
default: lcd.println(" other button ");
}
delay(500);
lcd.clear();
}
void loop()
{
if (irrecv.decode(&results)) // have we received an IR signal?
{
translateIR();
for (int z=0; z<2; z++) // ignore 2nd and 3rd signal repeat
{
irrecv.resume(); // receive the next value
}
}
}
And here it is in action:
You might be thinking “why would I want to make things appear on the LCD like that?”. The purpose of the example is to show how to react to various IR commands. You can replace the LCD display functions with other functions of your choosing.
At the start working with infra-red may have seemed to be complex, but with the previous two examples it should be quite simple by now. So there you have it, another useful way to control our Arduino systems. Hopefully you have some ideas on how to make use of this technology. In future articles we will examine creating and sending IR codes from our Arduino. So stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Furthermore, a big thanks to Ken Shirriff for his Arduino library.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Continue to learn about connecting your Arduino to the cellular network with the SM5100 GSM module shield. This is chapter twenty-seven of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
Updated 02/03/2013
Assumed understanding for this article is found in part one. If you have not already done so, please read and understand it. In this instalment we continue with bare projects which you can use as a framework for your own creations.
Reach out and control something
First we will discuss how to make something happen by a simple telephone call. And the best thing is that we don’t need the the GSM module to answer the telephone call (thereby saving money) – just let the module ring a few times. How is this possible? Very easily. Recall example 26.1 – we monitored the activity of the GSM module by using our terminal software. In this case what we need to do is have our Arduino examine the text coming in from the serial output of the GSM module, and look for a particular string of characters.
When we telephone the GSM module from another number, the module returns the text as shown in the image below (click to enlarge):
We want to look for the text “RING”, as (obviously) this means that the GSM shield has recognised the ring signal from the exchange. Therefore need our Arduino to count the number of rings for the particular telephone call being made to the module. (Memories – Many years ago we would use public telephones to send messages to each other. For example, after arriving at a foreign destination we would call home and let the phone ring five times then hang up – which meant we had arrived safely). Finally, once the GSM shield has received a set number of rings, we want the Arduino to do something.
From a software perspective, we need to examine each character as it is returned from the GSM shield. Once an “R” is received, we examine the next character. If it is an “I”, we examine the next character. If it is an “N”, we examine the next character. If it is a “G”, we know an inbound call is being attempted, and one ring has occurred. We can set the number of rings to wait until out desired function is called. In the following example, when the shield is called, it will call the function doSomething() after three rings.
The function doSomething() controls two LEDs, one red, one green. Every time the GSM module is called for 3 rings, the Arduino alternately turns on or off the LEDs. Using this sketch as an example, you now have the ability to turn basically anything on or off, or call your own particular function. Another example would be to return some type of data, for example you could dial in and have the Arduino send you a text message containing temperature data.
#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the Serial Port.
SoftwareSerial cell(2,3); //Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin.
int numring=0;
int comring=3;
int onoff=0; // 0 = off, 1 = on
void setup()
{
pinMode(12, OUTPUT);
pinMode(13, OUTPUT); // LEDs - off = red, on = green
digitalWrite(12, HIGH);
digitalWrite(13, LOW);
//Initialize serial port for communication.
cell.begin(9600);
}
void loop()
{
//If a character comes in from the cellular module...
if(cell.available() >0)
{
inchar=cell.read();
if (inchar=='R')
{
delay(10);
inchar=cell.read();
if (inchar=='I')
{
delay(10);
inchar=cell.read();
if (inchar=='N')
{
delay(10);
inchar=cell.read();
if (inchar=='G')
{
delay(10);
// So the phone (our GSM shield) has 'rung' once, i.e. if it were a real phone
// it would have sounded 'ring-ring'
numring++;
if (numring==comring)
{
numring=0; // reset ring counter
doSomething();
}
}
}
}
}
}
}
And now for a quick video demonstration. The first call is made, and the LEDs go from red (off) to green (on). A second call is made, and the LEDs go from green (on) to red (off). Although this may seem like an over-simplified example, with your existing Ardiuno knowledge you now have the ability to run any function by calling your GSM shield.
Control Digital I/O via SMS
Now although turning one thing on or off is convenient, how can we send more control information to our GSM module? For example, control four or more digital outputs at once? These sorts of commands can be achieved by the reception and analysis of text messages.
Doing so is similar to the method we used in example 27.1. Once again, we will analyse the characters being sent from the GSM module via its serial out. However, there are two AT commands we need to send to the GSM module before we can receive SMSs, and one afterwards. The first one you already know:
AT+CMGF=1
Which sets the SMS mode to text. The second command is:
AT+CNMI=3,3,0,0
This command tells the GSM module to immediately send any new SMS data to the serial out. An example of this is shown in the terminal capture below (click to enlarge):
Two text messages have been received since the module was turned on. You can see how the data is laid out. The blacked out number is the sender of the SMS. The number +61418706700 is the number for my carrier’s SMSC (short message service centre). Then we have the date and time. The next line is the contents of the text message – what we need to examine in our sketch.
The second text message in the example above is how we will structure our control SMS. Our sketch will wait for a # to come from the serial line, then consider the values after a, b, c and d – 0 for off, 1 for on. Finally, we need to send one more command to the GSM module after we have interpreted our SMS:
AT+CMGD=1,4
This deletes all the text messages from the SIM card. As there is a finite amount of storage space on the SIM, it is prudent to delete the incoming message after we have followed the instructions within. But now for our example. We will control four digital outputs, D9~12. For the sake of the exercise we are controlling an LED on each digital output, however you could do anything you like. Although the sketch may seem long and complex, it is not – just follow it through and you will see what is happening.
#include <SoftwareSerial.h>
char inchar; //Will hold the incoming character from the Serial Port.
SoftwareSerial cell(2,3); //Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin.
int led1 = 9;
int led2 = 10;
int led3 = 11;
int led4 = 12;
void setup()
{
// prepare the digital output pins
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
//Initialize GSM module serial port for communication.
cell.begin(9600);
delay(30000); // give time for GSM module to register on network etc.
cell.println("AT+CMGF=1"); // set SMS mode to text
delay(200);
cell.println("AT+CNMI=3,3,0,0"); // set module to send SMS data to serial out upon receipt
delay(200);
}
void loop()
{
//If a character comes in from the cellular module...
if(cell.available() >0)
{
inchar=cell.read();
if (inchar=='#')
{
delay(10);
inchar=cell.read();
if (inchar=='a')
{
delay(10);
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(led1, LOW);
}
else if (inchar=='1')
{
digitalWrite(led1, HIGH);
}
delay(10);
inchar=cell.read();
if (inchar=='b')
{
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(led2, LOW);
}
else if (inchar=='1')
{
digitalWrite(led2, HIGH);
}
delay(10);
inchar=cell.read();
if (inchar=='c')
{
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(led3, LOW);
}
else if (inchar=='1')
{
digitalWrite(led3, HIGH);
}
delay(10);
inchar=cell.read();
if (inchar=='d')
{
delay(10);
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(led4, LOW);
}
else if (inchar=='1')
{
digitalWrite(led4, HIGH);
}
delay(10);
}
}
cell.println("AT+CMGD=1,4"); // delete all SMS
}
}
}
}
}
And now for a video demonstration:
So there you have it – controlling your Arduino digital outputs via a normal telephone or SMS. Now it is up to you and your imagination to find something to control, sensor data to return, or get up to other shenanigans.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Connect your Arduino to the cellular network with the SM5100 GSM module shield. This is chapter twenty-six of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
Updated 18/03/2013
Introduction
The purpose of this tutorial is to have your Arduino to communicate over a GSM mobile telephone network using the SM5100B GSM Cellular Shield:
This is the first of several articles related to the SM5100B GSM shield. My goal is to illustrate various methods of interaction between an Arduino and the GSM cellular network using the shield, with which you can then use your existing knowledge to build upon those methods. Doing so isn’t easy – but it isn’t that difficult.
Stop! Please read first:
It is assumed that you have a solid understanding of how to program your Arduino. If not, start from chapter zero
Sending SMS messages and making phone calls cost real money, so it would be very wise to use a prepaid cellular account or one that allows a fair amount of calls/SMS
The GSM shield only works with “2G” GSM mobile networks operating on the 850, 900 and PCS1800 MHz frequencies. If in doubt, ask your carrier first
Australians – you can use any carrier’s SIM card, except for “Three”
Canadians – this doesn’t work with Sasktel
North Americans – check with your cellular carrier first if you can use third-party hardware (i.e. the shield)
I cannot offer design advice for your project nor technical support for this article.
If you are working on a college/university project and need specific help – talk to your tutors or academic staff. They get paid to help you.
Please don’t make an auto-dialler…
Getting started
As mentioned previously, we’re using the Sparkfun GSM shield with the SM5100B module. When you order the shield, don’t forget to order the stacking header pin set as they’re not included with the shield, and you’ll need to solder them on yourself. Power -the GSM shield can often require up to 2A of current in short bursts – especially when turned on, reset, or initiating a call. However your Arduino board can only supply just under 1A. It is highly recommended that you use an external regulated 5V power supply capable of delivering 2A of current – from an AC adaptor, large battery with power regulator, etc. Otherwise there is a very strong probability of damaging your shield and Arduino.
Ignore this at your own risk
When connecting this supply DO NOT use the DC socket on the Arduino. Instead, connect the 5V (positive) from the supply to the 5V pin on the GSM shield, and the negative to the GND pin.
If you’re looking for a more permanent or easy-to-wire solution, get yourself a DFRobot power shield:
This shield sits on top of your GSM shield (which sits on top of your Arduino). Before use you need to set it up:
The only jumpers that should be on the power shield are as shown in the image above;
Connect a power supply of between 9 and 35V DC to the blue terminal block at the bottom-left of the shield;
Connect a voltmeter/multimeter to the other blue terminal block at the top-left and adjust the potentiometer (blue thing between the terminal blocks) until the voltage measured is 5 volts; ignore the LEDs on the shield as they’re not that accurate;
Run a wire from the positive power output to the 5V pin on the shield, and run another one from the negative power output to a GND pin on the shield;
If you have the USB cable connected to your project while operating the GSM shield, remove the USB cable before turning off external power to the project.
Here’s what it looks like once assembled with the antenna:
Next – use an antenna! The wire hanging from the shield is not an antenna. YOU NEED THE ANTENNA! There are two choices. Either use the smaller one for areas where handheld mobile reception is acceptable, such as this one:
Or if you are in an area of weaker reception, use an external antenna such as that used on a motor vehicle. If you are using the larger vehicle-style aerial, you might find that the plug will not fit to the shield’s connector. For example, consider the following:
On the left is the end of the lead from the carphone aerial, the right is the lead from the GSM shield. Problem! The solution is in the centre: an FME male to SMA male adaptor. This one came from element-14, part number 1826209 (it is a Multicomp R23-014-00-002611000).
Furthermore, care needs to be taken with your GSM shield with regards to the aerial lead-module connection, it is very fragile:
And finally, download this document (.pdf). It contains all the AT and ERROR codes that will turn up when you least expect it. Please review it if you are presented with a code you are unsure about.
Wow – all those rules and warnings?
The sections above may sound a little authoritarian, however I want your project to be a success. With the previous iterations of the tutorial people just didn’t follow the instructions – so I hope you do
Are you using an Arduino Mega or Leonardo board?
Things are a little different for you. Those boards don’t support SoftwareSerial on digital pins 2 and 3 thus rendering the GSM shield a little trickier to use. Instead, bend back the D2 and D3 pins on the GSM shield as such (click image to enlarge):
Then run jumpers from D2 on the attached shield to D10 and another from D3 to D11. If you’re using the aforementioned power shield it would be on top of the GSM shield however the jumper wires would be the same. Finally in all the sketches, change the line SoftwareSerial cell(2,3); to SoftwareSerial cell(10,11); . If you have a Leonardo, get a Uno.
Initial check – does it work?
This may sound like a silly question, but considering the cost of the shield and the variables involved, it is a good idea to check if your setup is functioning correctly before moving on. From a hardware perspective for this article, you will need your Arduino board, the GSM shield with activated SIM card and an aerial, and a range of previously used components. Make sure your SIM card is set to not require a PIN when the phone is turned on. You can check and turn this requirement off with your cellphone. For our initial test, upload the following sketch:
char incoming_char=0; //Will hold the incoming character from the Serial Port.
SoftwareSerial cell(2,3); //Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin.
void setup()
{
//Initialize serial ports for communication.
Serial.begin(9600);
cell.begin(9600);
Serial.println("Starting SM5100B Communication...");
}
void loop()
{
//If a character comes in from the cellular module...
if(cell.available() >0)
{
incoming_char=cell.read(); //Get the character from the cellular serial port.
Serial.print(incoming_char); //Print the incoming character to the terminal.
}
//If a character is coming from the terminal to the Arduino...
if(Serial.available() >0)
{
incoming_char=Serial.read(); //Get the character coming from the terminal
cell.print(incoming_char); //Send the character to the cellular module.
}
}
Then connect the GSM shield, aerial, insert the SIM card and apply power. Open the serial monitor box in the Arduino IDE and you should be presented with the following:
It will take around fifteen to thirty seconds for the text above to appear in full. What you are being presented with is a log of the GSM module’s actions. But what do they all mean?
+SIND: 1 means the SIM card has been inserted;
the +SIND: 10 line shows the status of the in-module phone book. Nothing to worry about there for us at the moment;
+SIND: 11 means the module has registered with the cellular network
+SIND: 3 means the module is partially ready to communicate
and +SIND: 4 means the module is registered on the network, and ready to communicate
If your terminal returned a +SIND 8 instead of 4, that is OK, we’ll sort that out in a moment. From this point on, we will need to use a different terminal program, as the Arduino IDE’s serial monitor box isn’t made for full two-way communications. You will need a terminal program that can offer full two-way com port/serial communication. For those running MS Windows, an excellent option is available here. It’s free, however consider donating for the use of it. For other operating systems, people say this works well. So now let’s try it out with the terminal software. Close your Arduino IDE serial monitor box if still open, then run your terminal, set it to look at the same serial port as the Arduino IDE was. Ensure the settings are 9600, 8, N, 1. Then reset your Arduino and the following should appear:
The next step is to tell the GSM module which network frequency(ies) to use. Please download this document (.pdf), and view page 127. There is a range of frequency choices that our module can use. If you don’t know which one to use, contact the telephone company that your SIM card came from. Australia – use option 4. Choose your option, then enter
AT+SBAND=x
(where X is the value matching your required frequency) into the terminal software and click SEND. Then press reset on the Arduino and watch the terminal display. You should hopefully be presented with the same text as above, ending with +SIND: 4. If your module returns +SIND: 4, we’re ready to move forward.
Our next test is to call our shield. So, pick up a phone and call it. Your shield will return data to the terminal window, for example:
As you can see, the module returns what is happening. I let the originating phone “ring” twice, and the module received the caller ID data (sorry, blacked it out). Some telephone subscribers’ accounts don’t send caller ID data, so if you don’t see your number, no problem. “NO CARRIER” occurred when I ended the call. +SIND: 6,1 means the call ended and the SIM is ready.
Have your Arduino “call you”
The document (.pdf) we downloaded earlier contains a list of AT commands – consider this a guide to the language with which we instruct the GSM module to do things. Let’s try out some more commands before completing our initial test. The first one is:
ATDxxxxxx
which dials a telephone number xxxxxx. For example, to call (212)-8675309 use
ATD2128675309
The next one is
ATH
which “hangs up” or ends the call. So, let’s reach out and touch someone. In the terminal software, enter your ATDxxxxxxxx command, then hit send. Let your phone ring. Then enter ATH to end the call. If you are experimenting and want to hang up in a hurry, you can also hit reset on the Arduino and it will end the call as well as resetting the system. So by now you should realise the GSM module is controlled by these AT commands.
To use an AT command in a sketch, we use the function
A simple sketch to dial a telephone number, wait, then hang up. Replace xxxxxxxx with the number you wish to call.
#include <SoftwareSerial.h>
SoftwareSerial cell(2,3);
void setup()
{
cell.begin(9600);
delay(25000); // give the GSM module time to initialise, locate network etc.
// this delay time varies. Use example 26.1 sketch to measure the amount
// of time from board reset to SIND: 4, then add five seconds just in case
}
void loop()
{
cell.println("ATDxxxxxxxxx"); // dial the phone number xxxxxxxxx
// change xxxxxxx to your desired phone number (with area code)
delay(20000); // wait 20 seconds.
cell.println("ATH"); // end call
do // remove this loop at your peril
{
delay(1);
}
while (1>0);
}
The sketch in example 26.2 assumes that all is well with regards to the GSM module, that is the SIM card is ok, there is reception, etc. The delay function in void setup() is used to allow time for the module to wake up and get connected to the network. Later on we will read the messages from the GSM module to allow our sketches to deal with errors and so on. However, you can see how we can simply dial a telephone. You could now have a home alarm system that can call you upon an event happening, etc.
Send an SMS from your Arduino
Another popular function is the SMS or short message service, or text messaging. Before moving forward, download and install Meir Michanie’s SerialGSM Arduino library from here.
Sending a text message is incredibly simple – consider the following sketch:
void sendSMS()
{
cell.Verbose(true); // used for debugging
cell.Boot();
cell.FwdSMS2Serial();
cell.Rcpt("+xxxxxxxxx"); // replace xxxxxxxxx with the recipient's cellular number
cell.Message("Contents of your text message");
cell.SendSMS();
}
void loop()
{
sendSMS();
do // remove this loop at your peril
{
delay(1);
}
while (1>0);
}
It’s super-simple – just change the phone number to send the text message, and of course the message you want to send. The phone numbers must be in international format, e.g. Australia 0418 123456 is +61418123456 or USA (609) 8675309 is +16098675309.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
In this review we examine an easy to build kit from adafruit industries that offers literally hours and hours of fun, if you like to get up to some mischief – the TV-B-Gone. This fascinating little device is basically an infra-red remote control for televisions and some monitors. It has a microcontroller programmed with the “off” code for a wide range of display brands, and four very strong infra-red transmitting LEDs, two with a wide beam, and two with a narrow but longer beam.
Here is the little culprit in standard assembled form:
It is a very easy kit to assemble, once again the team at adafruit have published an extensive amount of information, from assembly tutorials to how it works, and even the design itself as the kit is open-source hardware. So in this article you can follow the assembly, and use of this bag of fun.
As usual, this kit arrives in a resealable, anti-static bag. After ensuring I had the correct parts, from the documentation on the adafruit website, it was time to follow the simple instructions and start getting it together. Now this will be the second time I have built a TV-B-Gone… the first one is in the photo above, and had me removed from a department store (thanks Myer…) – so this time I am rebuilding it to fit inside a typical baseball cap.
Soldering it was quite simple, the PCB is solder-masked and has a very well detailed silk-screen:
Just following the instructions, and being careful not to rush is the key. Another feature of adafruit kits is that the are designed very well with regards to troubleshooting. For example, you have the opportunity to test it before finishing. So at this stage you can fit the AA cells and power it up, if the LED blinks you’re all good:
And we’re done… almost.
For installation into the hat, the button and the LEDs will need to be a distance away from the PCB. At this stage I was not sure where to put the button, so for now it can stay on the side of the cap:
Naturally you can use any momentary push button, however I will use the included example (above) with a length of wire. With this style of hat, especially a black one, slight bulges underneath the surface do not seem that apparent, however it is wiser to spread out the entire unit:
Although thinner AAA cells could be used for the power supply, for a good day’s action you will want the extra capacity of AA cells, so we’ll stick with them for now. The next step was to wire up the LEDs. They were connected individually to the PCB with lengths of wire, and heatshrink was used to insulate and darken the legs:
And finally the finished product, ready for insertion into a piece of clothing, or in our case – a cap:
At this point it was time to take it for a test toast. The quickest way to test an infra-red transmitter is to look at the LEDs through a digital camera – it can display the infra-red wavelengths whereas the human eye cannot see them. For example:
Those LEDs can get very bright (in infra-red terms), and is also how night-illumination for digital security cameras work. If you had a lot of those LEDs pointing at a security camera at night, you could blind it. That gives me an idea…
Anyway…
Assembling the kit in this format gives you lots of options for hiding it. For example, you could:
put the PCB and power in a jacket’s inside pocket, and have the LEDs poke out the neck;
place them in a cap as we are;
use a large ladies’ handbag, with the LEDs out the top, and the button underneath a handle;
sew the LEDs into the head-cover of a hooded jacket (with some longer leads) and have the PCB, power and button in the pockets
So here are the LEDs mounted under the brim of the cap.
If you are going to staple them in, be careful not to puncture the wires. The ends of the staple should come through to the top of the brim – in this case I covered them with black ink from a felt pen so they would blend in. The button lead’s position is down to personal preference, in my case the button is just poking out next to the strap on the back of the cap. So all I need to do is appear to scratch the back of my head to activate the TV-B-Gone.
And here is the finished product, with an unfinished author:
Well by now you want to see it working. So here you are… I went on a field trip wandering about the central business district of Brisbane, Australia:
My apologies for the shaky footage, doing this isn’t something you can really capture with a camera and a tripod. The problem was getting close enough, or most places had either covered their IR receiver, had a brand of TV not recognised by the TV-B-Gone, or used a large monitor instead of a television. But it was fun nevertheless.
In conclusion, this is an easy to assemble kit which is fun and certainly will get you into harmless trouble. Again, this is the type of kit that would be good for those who are being introduced to the fascinating world of electronics (etc) as it is quick to build, and does something with the “real world” that young people love so much. Or anyone else for that matter.
As much fun as it is to switch off televisions and advertising monitors, I would hope that end users will still be responsible with their TV-B-Gone use. Please head into a department store, your favourite eatery, coffee shop or mall and switch off the TVs. However, please do not turn off displays in railway stations, airports or other places where the authorities will take offence. You will get in real trouble. Or if you’re feeling suicidal, go switch off the TVs at the OTB.
[Note - this kit was purchased by myself personally and reviewed without notifying the manufacturer or retailer]
In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.