t r o n i x s t u f f

fun and learning with electronics

Book – “Arduino Workshop – A Hands-On Introduction with 65 Projects”

Over the last few years I’ve been writing a few Arduino tutorials, and during this time many people have mentioned that I should write a book. And now thanks to the team from No Starch Press this recommendation has morphed into my new book – “Arduino Workshop“:

shot11

Although there are seemingly endless Arduino tutorials and articles on the Internet, Arduino Workshop offers a nicely edited and curated path for the beginner to learn from and have fun. It’s a hands-on introduction to Arduino with 65 projects – from simple LED use right through to RFID, Internet connection, working with cellular communications, and much more.

Each project is explained in detail, explaining how the hardware an Arduino code works together. The reader doesn’t need any expensive tools or workspaces, and all the parts used are available from almost any electronics retailer. Furthermore all of the projects can be finished without soldering, so it’s safe for readers of all ages.

The editing team and myself have worked hard to make the book perfect for those without any electronics or Arduino experience at all, and it makes a great gift for someone to get them started. After working through the 65 projects the reader will have gained enough knowledge and confidence to create many things – and to continue researching on their own. Or if you’ve been enjoying the results of my thousands of hours of work here at tronixstuff, you can show your appreciation by ordering a copy for yourself or as a gift :)

You can review the table of contents, index and download a sample chapter from the Arduino Workshop website.

Arduino Workshop is available from No Starch Press in printed or ebook (PDF, Mobi, and ePub) formats. Ebooks are also included with the printed orders so you can get started immediately.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, 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.

May 2, 2013 Posted by | arduino, book, books, cellular, clocks, display, distance, ds1307, DS3232, education, EEPROM, freetronics, GPS, graphic, GSM, hardware hacking, I2C, internet, LCD, learning electronics, lesson, numeric keypad, part review, product review, projects, RDM630, RDM6300, relay, review, sensor, servo, SMS, time clock, timing, tronixstuff, tutorial, twitter, wireless, xbee | , , , , , , , , , , , , , , , , , , | 11 Comments

Tutorial: Control AC outlets via SMS

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.

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 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:

Example 33.1

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:

Example 33.2

#include <SoftwareSerial.h> 
char inchar; 
SoftwareSerial cell(2,3);
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);
}
 delay(10);
 inchar=cell.read(); 
 cell.println("AT+CMGD=1,4"); // delete all SMS
 }
 }
 }
 }
}

 

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 twitterGoogle+, 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.

April 24, 2011 Posted by | AC power, arduino, CEL-00675, CEL-09607, cellphone hacking, cellular, GSM, hardware hacking, SMS, tutorial | , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | Leave a Comment

Tutorial: Arduino and GSM Cellular – Part Two

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.

Example 27.1

#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 doSomething()
{
 if (onoff==0)
 {
 onoff=1;
 digitalWrite(12, HIGH);
 digitalWrite(13, LOW);
 } 
 else
 if (onoff==1)
 {
 onoff=0;
 digitalWrite(12, LOW);
 digitalWrite(13, HIGH);
 }
}
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.

Example 27.2

 #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.

If you enjoyed this article, you may find this of interest – controlling AC power outlets via SMS.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, 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.

January 31, 2011 Posted by | arduino, CEL-00675, CEL-09607, cellphone hacking, cellular, GSM, hardware hacking, microcontrollers, SMS, tutorial | , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | Leave a Comment

Tutorial: Arduino and GSM Cellular – Part One

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
  • Read the “boring stuff” section on my About page
  • 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:

  1. The only jumpers that should be on the power shield are as shown in the image above;
  2. Connect a power supply of between 9 and 35V DC to the blue terminal block at the bottom-left of the shield;
  3. 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;
  4. 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;
  5. 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:

Example 26.1

#include <SoftwareSerial.h>
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

cell.println()

for example, to dial a phone number, we would use

cell.println("ATD2128675309");

To demonstrate this in a sketch, consider:

Example 26.2

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:

Example 26.3

#include <SerialGSM.h>
#include <SoftwareSerial.h>
SerialGSM cell(2,3);
void setup()
{ 
 delay(30000); // wait for GSM module
 cell.begin(9600);
}
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.

Well that is all we have time for in this instalment.  Now you can move onto GSM and Arduino – part two.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, 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.

January 19, 2011 Posted by | arduino, CEL-00675, CEL-09607, cellphone hacking, cellular, GSM, SMS, tronixstuff, tutorial | , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | 20 Comments

Tutorial: Using analog input for multiple buttons

This is chapter twenty-five 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. Please note from November 1, 2010 files from tutorials will be found here.

[Updated 14/03/2013]

The purpose of this article is demonstrate how you can read many push buttons (used for user-input) using only one analog input pin. This will allow you to save digital I/O pins for other uses such as LCD modules and so on. Hopefully you recall how we used analogRead() in chapter one, and how we used a potentiometer to control menu options in exercise 10.1. For this article, we will be looking at reading individual presses, not simultaneous (i.e. detecting multiple button presses).

To recap, an analog input pin is connected to an analog to digital (ADC) converter in our Arduino’s microcontroller. It has a ten bit resolution, and can return a numerical value between 0 and 1023 which relates to an analog voltage being read of between 0 and 5 volts DC.

Example 25.1

With this sketch:

/*  Example 25.1 - Demonstrating analogRead()
http://tronixstuff.com/tutorials > chapter 25
CC by-sa-nc*/
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 2, 3);
int a=0;
void setup()
{
lcd.begin(20, 4);
pinMode(A5, INPUT_PULLUP);
}
void loop()
{
a = analogRead(5);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("  analogRead() ");
lcd.setCursor(0,1);
lcd.print("  value is :");
lcd.print(a);
delay(250);
}

and in the following short video, we have demonstrated the possible values returned by measuring the voltage from the centre pin of a 10k ohm potentiometer, which is connected between 5V and GND:

As the potentiometer’s resistance decreases, the value returned by analogRead() increases. Therefore at certain resistance values, analogRead() will return certain numerical values. So, if we created a circuit with (for example) five buttons that allowed various voltages to be read by an analog pin, each voltage read would cause analogRead() to return a particular value. And thus we can read the status of a number of buttons using one analog pin.

Example 25.2

The following circuit is an example of using five buttons on one analog input, using the sketch from example 25.1:

And here it is in action:

Where is the current coming from? Using pinMode(A5, INPUT_PULLUP); turns on the internal pull-up resistor in the microcontroller, which gives us ~4.8V to use. Some of you may have notice that when the right-most button is pressed, there is a direct short between A5 and GND. When that button is depressed, the current flow is less than one milliamp due to the pull-up resistor protecting us from a short circuit. Also note that you don’t have to use A5, any analog pin is fine.

As shown in the previous video clip, the values returned by analogRead() were:

  • 1023 for nothing pressed (default state)
  • 454 for button one
  • 382 for button two
  • 291 for button three
  • 168 for button four
  • 0 for button five

So for our sketches to react to the various button presses, they need to make decisions based on the value returned by analogRead(). Keeping all the resistors at the same value gives us a pretty fair spread between values, however the values can change slightly due to the tolerance of resistors and parasitic resistance in the circuit.

So after making a prototype circuit, you should determine the values for each button, and then have your sketch look at a range of values when reading the analog pin. Doing so becomes more important if you are producing more than one of your project, as resistors of the same value from the same batch can still vary slightly.

Example 25.3

Using the circuit from example 25.2, we will use a function to read the buttons and return the button number for the sketch to act upon.

/*  Example 25.3 - Digital buttons with analog input 
http://tronixstuff.com/tutorials > chapter 25 CC by-sa-nc */
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 2, 3);
int a=0;
void setup()
{
lcd.begin(20, 4);
     pinMode(A5, INPUT_PULLUP); // sets analog pin for input 

} 

int readButtons(int pin)
 // returns the button number pressed, or zero for none pressed 
 // int pin is the analog pin number to read 
{
int b,c = 0;
c=analogRead(pin); // get the analog value  if (c>1000)
{
b=0; // buttons have not been pressed
}   else
if (c>440 && c<470)
{
b=1; // button 1 pressed
}     else
if (c<400 && c>370)
{
b=2; // button 2 pressed
}       else
if (c>280 && c<310)
{
b=3; // button 3 pressed
}         else
if (c>150 && c<180)
{
b=4; // button 4 pressed
}           else
if (c<20)
{
b=5; // button 5 pressed
}
return b;
}
void loop()
{
a=readButtons(5);
lcd.clear();
if (a==0) // no buttons pressed
{
lcd.setCursor(0,1);
lcd.print("Press a button");
}   else
if (a>0) // someone pressed a button!
{
lcd.setCursor(0,2);
lcd.print("Pressed button ");
lcd.print(a);
}
delay(1000); // give the human time to read LCD
}

And now our video demonstration:

So now you have a useful method for receiving input via buttons without wasting many digital input pins. I hope you found this article useful or at least interesting.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, 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.

January 11, 2011 Posted by | arduino, learning electronics, microcontrollers, tutorial | , , , , , , , , , , , , , , , , , , , , , | Leave a Comment

Tutorial: Arduino and monochrome LCDs

Please note that the tutorials are not currently compatible with Arduino IDE v1.0. Please continue to use v22 or v23 until further notice. 

This is chapter twenty-four 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. Please note from November 1, 2010 files from tutorials will be found here.

Welcome back fellow arduidans!

The purpose of this article is to summarise a range of affordable monochrome liquid-crystal display units that are available to work with our Arduino; and to replace the section about LCDs in chapter two of this series. We will first examine some fixed-character and then graphical LCD units in this article. So let’s go!

Fixed-character LCD modules

When shopping around for LCD modules, these will usually be the the most common found in retail outlets. Their size is normally measured by the number of columns and rows of characters in the display. For example, the three LCDs below are 8×2, 16×2 and 20×4 characters in size:

Currently, most LCDs should have a backlight of some sort, however you may come across some heavily-discounted models on (for example) eBay that are not. Character, background and backlight colours can vary, for example:

Interfacing these screens with our Arduino boards is very easy, and there are several ways to do so. These interface types can include four- and eight-bit parallel, three-wire,  serial, I2C and SPI interfaces; and the LCD price is usually inversely proportional to the ease of interface (that is, parallel are usually the cheapest).

Four-bit parallel interface

This is the cheapest method of interface, and our first example for this article. Your LCD will need a certain type of controller IC called a Hitachi HD44780 or compatible such as the KS0066. From a hardware perspective, there are sixteen pins on the LCD. These are usually in one row:

… or two rows of eight:

The pin labels for our example are the following:

  1. GND
  2. 5V (careful! Some LCDs use 3.3 volts – adjust according to LCD data sheet from supplier)
  3. Contrast
  4. RS
  5. RW
  6. Enable
  7. DB0 (pins DB0~DB7 are the data lines)
  8. DB1
  9. DB2
  10. DB3
  11. DB4
  12. DB5
  13. DB6
  14. DB7
  15. backlight + (unused on non-backlit LCDs) – again, check your LCD data sheet as backlight voltages can vary.
  16. backlight GND (unused on non-backlit LCDs)

As always, check your LCD’s data sheet before wiring it up.

Some LCDs may also have the pinout details on their PCB if you are lucky, however it can be hard to decipher:

Now let’s connect our example 16×2 screen to our Arduino using the following diagram.

Our LCD runs from 5V and also has a 5V backlight – yours may differ, so check the datasheet:

(Circuit layout created using Fritzing)

Notice how we have used six digital output pins on the Arduino, plus ground and 5V. The 10k ohm potentiometer connected between LCD pins 2, 3 and 5 is used to adjust the display contrast. You can use any digital out pins on your Arduino, just remember to take note of which ones are connected to the LCD as you will need to alter a function in your sketch. If your backlight is 3.3V, you can use the 3.3V pin on the Arduino.

From a software perspective, we need to use the LiquidCrystal() library. This library should be pre-installed with the Arduino IDE. So in the start of your sketch, add the following line:

#include <LiquidCrystal.h>

Next, you need to create a variable for our LCD module, and tell the sketch which pins are connected to which digital output pins. This is done with the following function:

LiquidCrystal lcd(4,5,6,7,8,9);

The parameters in the brackets define which digital output pins connect to (in order) LCD pins: RS, enable, D4, D5, D6, and D7.

Finally, in your void setup(), add the line:

lcd.begin(16,2);

This tells the sketch the dimensions in characters (columns, rows) of our LCD module defined as the variable lcd.

Example 24.1

In this example we will get started with out LCD by using the basic setup and functions. To save space the explanation of each function will be in the sketch itself. Please note that you do not have to use an Arduino Mega – it is used in this article as my usual Arduino boards are occupied elsewhere.

/*
Example 24.1 - LCD demonstration
http://tronixstuff.com/tutorials > Chapter 24
CC by-sa-nc liquidCrystal library originally added 18 Apr 2008 by David A. Mellis
library modified 5 Jul 2009   by Limor Fried (http://www.ladyada.net, http://www.adafruit.com)
*/
#include <LiquidCrystal.h> // we need this library for the LCD commands
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(4,5,6,7,8,9); // define our LCD and which pins to user
int a = 63;
int d = 3000; // used for display delayfloat
float b = 3.1415926;
void setup()
{
lcd.begin(16, 2); // need to specify how many columns and rows are in the LCD unit
lcd.clear();      // this clears the LCD. You can use this at any time
}
void loop()
{
lcd.clear();
lcd.setCursor(0,0);
// positions starting point on LCD, column 0, row 0 (that is, the top left of our LCD)
lcd.print("Hello!");
// prints "Hello" at the LCD's cursor position defined above
lcd.setCursor(0,1);
// positions starting point on LCD, column 0, row 1 (that is, the bottom left of our LCD)
lcd.println("This is fun     ");
// note the rest of the line is padded out with spaces
delay(d);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("a = ");
lcd.print(a); // this will immediately follow "a = "
lcd.setCursor(0,1);
lcd.print("pi = ");
lcd.print(b,7);
// the 7 means 7 decimal places. You can also replace this with DEC, HEX, BIN as with
// other *.print functions, as such:
delay(d);
lcd.clear();
lcd.home(); // sets cursor back to position 0,0 - same as lcd.setCursor(0,0);
lcd.print("a (HEX) = ");
lcd.print(a, HEX); // this will immediately follow "a = "
lcd.setCursor(0,1);
lcd.print("a (BIN) = ");
lcd.print(a,BIN);
delay(d);
lcd.noDisplay(); // turns off the display, leaving currently-displayed data as is
delay(d);        // however this does not control the backlight
lcd.display();   // resumes display
delay(d);
}

And here is a quick video of the example 24.1 sketch in action:

There are also a some special effects that we can take advantage of with out display units – in that we can actually define our own characters (up to eight per sketch). That is, control the individual dots (or pixels) that make up each character. With the our character displays, each character is made up of five columns of eight rows of pixels, as illustrated in the close-up below:

In order to create our characters, we need to define which pixels are on and which are off. This is easily done with the use of an array (array? see chapter four). For example, to create a solid block character as shown in the image above, our array would look like:

byte a[8] = {
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111}

Notice how we have eight elements, each representing a row (from top to bottom), and each element has five bits – representing the pixel column for each row. The next step is to reference the custom character’s array to a reference number (0~7) using the following function within void setup():

lcd.createChar(0,a);

Now when you want to display the custom character, use the following function:

lcd.write(0);

where 0 is the memory position of the character to display.

To help make things easier, there is a small website that does the array element creation for you.

Example 24.2

Now let’s display a couple of custom characters to get a feel for how they work. In the following sketch there are three defined characters:

/* Example 24.2 - LCD custom character demonstration
 http://tronixstuff.com/tutorials > Chapter 24 CC by-sa-nc
 liquidCrystal library originally added 18 Apr 2008 by David A. Mellis
 library modified 5 Jul 2009  by Limor Fried (http://www.ladyada.net, http://www.adafruit.com)
*/
#include <LiquidCrystal.h> // we need this library for the LCD commands
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(4,5,6,7,8,9); // define our LCD and which pins to use
int d = 3000; // used for display delay
byte a[8] = {  B00000,  B00000,  B00000,  B00100,  B00100,    B00000,  B00000,  B00000};
byte b[8] = {  B00000,  B00000,  B10001,  B10001,  B10001,  B10001,  B00000,  B00000};
byte c[8] = {  B11111,  B10001,  B10001,  B10001,  B10001,  B10001,  B10001,  B11111};
void setup()
{
lcd.createChar(0,a); // define our characters into the sketch as variables
lcd.createChar(1,b);
lcd.createChar(2,c);
lcd.begin(16, 2); // need to specify how many columns and rows are in the LCD unit
lcd.clear();      // this clears the LCD. You can use this at any time
}
void loop()
{
for (int z=0; z<16; z++)
{
lcd.setCursor(z,0);
lcd.write(0);  // write the first character
delay(250);
lcd.setCursor(z,0);
lcd.write(1);  // write the second character
delay(250);
lcd.setCursor(z,0);
lcd.write(2);  // write the third character
delay(250);
lcd.setCursor(z,0);
lcd.write(1); // write the second character
delay(250);
lcd.setCursor(z,0);
lcd.write(0);  // write the first character
delay(250);
}
delay(1000);
lcd.clear();
}

And here is a quick video of the example 24.2 sketch in action:

So there you have it – a summary of the standard parallel method of connecting an LCD to your Arduino. Now let’s look at the next type:

Three-wire LCD interface

If you cannot spare many digital output pins on your Arduino, only need basic text display and don’t want to pay for a serial or I2C LCD, this could be an option for you. A 4094 shift register IC allows use of the example HD44780 LCD with only three digital output pins from your Arduino. The hardware is connected as such:


And in real life:

From a software perspective, we need to use the LCD3Wire library, which you can download from here. To install the library, copy the folder within the .zip file to your system’s \Arduino-2x\hardware\libraries folder and restart the Arduino IDE. Then, in the start of your sketch, add the following line:

#include <LCD3Wire.h>

Next, you need to create a variable for our LCD module, and tell the sketch which of the 4094′s pins are connected to which digital output pins as well as define how many physical lines are in the LCD module. This is done with the following function:

LCD3Wire lcd = LCD3Wire(2, 11, 12, 10); The parameters in the brackets are the number of lines in the LCD and the digital output pins connected to 4094 pin numbers 2, 1 and 3.

Finally, in your void setup(), add the line:

lcd.init();

The number of available LCD functions in the LCD3wire library are few – that is the current trade-off with using this method of LCD connection … you lose LCD functions but gain Arduino output pins. In the following example, we will demonstrate all of the available functions within the LCD3Wire library.

Example 24.3

/*
Example 24.3 - 3-wire LCD demonstration
http://tronixstuff.com/tutorials > chapter 24
Contains copyleft code from http://www.arduino.cc/playground/Code/LCD3wires
and LCD3Wire library  */
#include  // we need this library for the LCD commands
LCD3Wire lcd = LCD3Wire(2, 11, 12, 10); //create object to control an LCD.
void setup()  {
lcd.init();
}
void loop()
{
lcd.printIn("LCD3Wire library"); // displays text on the LCD
lcd.cursorTo(2,0);  // rows are 1... and columns are 0...
lcd.printIn("-tronixstuff.com");
delay(1000);
lcd.leftScroll(16,500);
// scrolls the entire display 16 chars to left, 100ms per character-shift
delay(1000);
lcd.clear(); // clears the display
}  

And as always, let’s see it in action. The LCD update speed is somewhat slower than using the parallel interface, this is due to the extra handling of the data by the 4094 IC:

Now for some real fun with:

Graphic LCD modules

(Un)fortunately there are many graphic LCD modules on the market. To keep things relatively simple, we will examine two – one with a parallel data interface and one with a serial data interface.

Parallel interface

Our example in this case is a 128 by 64 pixel unit with a KS0108B parallel interface:

For the more technically-minded here is the data sheet. From a hardware perspective there are twenty interface pins, and we’re going to use all of them. For breadboard use, solder in a row of header pins to save your sanity!

This particular unit runs from 5V and also has a 5V backlight. Yours may vary, so check and reduce backlight voltage if different.

You will again need a 10k ohm potentiometer to adjust the display contrast. Looking at the image above, the pin numbering runs from left to right. For our examples, please connect the LCD pins to the following Arduino Uno/Duemilanove sockets:

  1. 5V
  2. GND
  3. centre pin of 10k ohm potentiometer
  4. D8
  5. D9
  6. D10
  7. D11
  8. D4
  9. D5
  10. D6
  11. D7
  12. A0
  13. A1
  14. RST
  15. A2
  16. A3
  17. A4
  18. outer leg of potentiometer; connect other leg to GND
  19. 5V
  20. GND

A quick measurement of current shows my TwentyTen board and LCD uses 20mA with the backlight off and 160mA with it on. The display is certainly readable with the backlight off, but it looks a lot better with it on.

From a software perspective we have another library to install. By now you should be able to install a library, so download this KS0108 library and install it as usual. Once again, there are several functions that need to be called in order to activate our LCD. The first of these being:

GLCD.Init(NON_INVERTED);

which is placed within void setup(); The parameter sets the default pixel status. That is, with NON_INVERTED, the default display is as you would expect, pixels off unless activated; whereas INVERTED causes all pixels to be on by default, and turned off when activated. Unlike the character LCDs we don’t have to create an instance of the LCD in software, nor tell the sketch which pins to use – this is already done automatically. Also please remember that whenever coordinates are involved with the display, the X-axis is 0~127 and the Y-axis is 0~63.

There are many functions available to use with the KS0108 library, so let’s try a few of them out in this first example. Once again, we will leave the explanation in the sketch, or refer to the library’s page in the Arduino website. My creative levels are not that high, so the goal is to show you how to use the functions, then you can be creative on your own time :)

Example 24.4

This example demonstrate a simpler variety of graphic display functions.

/*  Example 24.4 - KS0108 Graphic LCD demonstration
http://tronixstuff.com/tutorials > chapter 24  CC by-sa-nc
*/
#include <ks0108.h>  // library header
int xc, yc = 0;
int d=1000; // for delay use
void setup()
{
GLCD.Init(NON_INVERTED);   // initialise the library with pixel default as off
GLCD.ClearScreen();        // clear the LCD
randomSeed(analogRead(5));
}
void loop()
{
GLCD.DrawRect(0, 0, 127, 63, BLACK);
// draw an open rectangle that spans the extremties of the LCD
GLCD.DrawRect(10, 10, 117, 53, BLACK);
GLCD.DrawRect(20, 20, 107, 43, BLACK);
GLCD.DrawRect(30, 30, 97, 33, BLACK);
delay(d);
GLCD.ClearScreen();  // clear the LCD
for (int a=1; a<20; a++)
{
GLCD.DrawCircle(63,31,a,BLACK);
// draws a circle with centre at 61,31; radius of a, with black pixels
delay(d-800);
GLCD.DrawCircle(63,31,a,WHITE); // draws the same circle with the pixels off
}
delay(d);
GLCD.ClearScreen();  // clear the LCD
for (int a=0; a<128; a++)
{
GLCD.DrawVertLine(a, 0, 63, BLACK);
// draws a vertical line from xy position a, 0 of length 63
delay(d-950);
}
delay(d-800);
for (int a=0; a<128; a++)
{
GLCD.DrawVertLine(a, 0, 63, WHITE);
delay(d-950);
}
GLCD.ClearScreen();  // clear the LCD
for (int a=0; a<64; a++)
{
GLCD.DrawHoriLine(0, a, 127, BLACK);
// draws a horizontal line from xy position 0, a of length 127
delay(d-950);
}
for (int a=0; a<64; a++)
{
GLCD.DrawHoriLine(0, a, 127, WHITE);
delay(d-950);
}
GLCD.ClearScreen();  // clear the LCD
GLCD.DrawRoundRect(30, 30, 20,20, 5,BLACK);
// draw a rectangle with rounded edges: x, y, width, height, radius of rounded edge, colour
GLCD.DrawRoundRect(60, 30, 20,20, 5,BLACK);
delay(d);
GLCD.ClearScreen();  // clear the LCD
delay(d);
GLCD.FillRect(30, 30, 30, 10, BLACK);
// draws a filled rectangle: x, y, width, height, colour
delay(d);
GLCD.ClearScreen();  // clear the LCD
for (int a=0; a<1000; a++)
{
xc=random(0,127);
yc=random(0, 63);
GLCD.SetDot(xc, yc, BLACK);
// turn on a pixel at xc, yc);
delay(2);
}
GLCD.ClearScreen();
// clear the LCD
}

Now let’s see all of that in action:

You can also send normal characters to your KS0108 LCD. Doing so allows you to display much more information in a smaller physical size than using a character  LCD. Furthermore you can mix graphical functions with character text functions – with some careful display planning you can create quite professional installations. With a standard 5×7 pixel font, you can have eight rows of twenty-one characters each. Doing so is quite easy, we need to use another two #include statements which are detailed in the following example. You don’t need to install any more library files to use this example. Once again, function descriptions are in the sketch.

Example 24.5

/*  Example 24.5 - KS0108 Graphic LCD demonstration #2
http://tronixstuff.com/tutorials > chapter 24  CC by-sa-nc
*/
#include <ks0108.h> //  library for LCD
#include "SystemFont5x7.h"
// we need this for character display, included with ks0108.h download
void setup()
{
GLCD.Init(NON_INVERTED);   // load the GLCD library
GLCD.ClearScreen();
GLCD.SelectFont(System5x7);
// choose font to use (note this needs to match the #include above
}
int j = 24;
void loop()
{
GLCD.ClearScreen();
GLCD.DrawRect(0, 0, 127, 63,BLACK);
GLCD.CursorTo(1, 1);
// set cursor to top left of LCD (uses character coordinates
// not pixel coordinates
GLCD.Puts("Hello, world."); // sends strings to LCD. Does not wrap to next line!
GLCD.CursorTo(1, 2);
GLCD.Puts("I hope you are ");
GLCD.CursorTo(1, 3);
GLCD.Puts("enjoying this");
GLCD.CursorTo(1, 4);
GLCD.Puts("series of lessons. ");
GLCD.CursorTo(1, 5);
GLCD.Puts("This is from ");
GLCD.CursorTo(1, 6);
GLCD.Puts("chapter ");
GLCD.PrintNumber(j); // sends an integer to the LCD. Does not wrap to next line either
GLCD.Puts(".");
delay(3000);
GLCD.ClearScreen();
for (int xx=0; xx<21; xx++)
{
for (int yy=0; yy<8; yy++)
{
GLCD.CursorTo(xx, yy);  // position the text cursor
GLCD.Puts("#");
delay(50);
}
}
delay(1000);
GLCD.ClearScreen();
}

Again,  let’s see all of that in action:

If you’re looking for a very simple way of using character LCD modules, check this out.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, 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.

January 8, 2011 Posted by | arduino, education, LCD, LCD-00710, learning electronics, microcontrollers, tutorial | , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | 53 Comments

Welcome to t r o n i x s t u f f

Welcome to the tronixstuff website. Regular articles are published about many things, including analogue and digital electronics, electronic kits, part reviews – and you can also follow our popular series of Arduino tutorials. The latest posts are below, and at your top-right are indexes to previous articles. On the right are ways to subscribe for new post notifications,  as well as links to our Google Group for discussion. Look around, learn something. And remember – there is so much more than just Arduino! (“Arduino” is a trademark of Arduino Team).

Before following any tutorials, please read and understand the boring stuffYou follow anything here at your own risk.

June 27, 2010 Posted by | about | , , , , , , , , , , , , , , | Comments Off

   

Follow

Get every new post delivered to your Inbox.

Join 3,843 other followers

%d bloggers like this: