Posts with «tronixstuff» label

Tutorial – L298N Dual Motor Controller Modules and Arduino

Learn how to use inexpensive L298N motor control modules to drive DC and stepper motors with Arduino. This is chapter fifty-nine of our huge Arduino tutorial series.

You don’t have to spend a lot of money to control motors with an Arduino or compatible board. After some hunting around we found a neat motor control module based on the L298N H-bridge IC that can allows you to control the speed and direction of two DC motors, or control one bipolar stepper motor with ease.

The L298N H-bridge module can be used with motors that have a voltage of between 5 and 35V DC. With the module used in this tutorial, there is also an onboard 5V regulator, so if your supply voltage is up to 12V you can also source 5V from the board.

So let’s get started!

First we’ll run through the connections, then explain how to control DC motors then a stepper motor. At this point, review the connections on the L298N H-bridge module.

Consider the following image – match the numbers against the list below the image:

  1. DC motor 1 “+” or stepper motor A+
  2. DC motor 1 “-” or stepper motor A-
  3. 12V jumper – remove this if using a supply voltage greater than 12V DC. This enables power to the onboard 5V regulator
  4. Connect your motor supply voltage here, maximum of 35V DC. Remove 12V jumper if >12V DC
  5. GND
  6. 5V output if 12V jumper in place, ideal for powering your Arduino (etc)
  7. DC motor 1 enable jumper. Leave this in place when using a stepper motor. Connect to PWM output for DC motor speed control.
  8. IN1
  9. IN2
  10. IN3
  11. IN4
  12. DC motor 2 enable jumper. Leave this in place when using a stepper motor. Connect to PWM output for DC motor speed control.
  13. DC motor 2 “+” or stepper motor B+
  14. DC motor 2 “-” or stepper motor B-

Controlling DC Motors

To control one or two DC motors is quite easy with the L298N H-bridge module. First connect each motor to the A and B connections on the L298N module. If you’re using two motors for a robot (etc) ensure that the polarity of the motors is the same on both inputs. Otherwise you may need to swap them over when you set both motors to forward and one goes backwards!

Next, connect your power supply – the positive to pin 4 on the module and negative/GND to pin 5. If you supply is up to 12V you can leave in the 12V jumper (point 3 in the image above) and 5V will be available from pin 6 on the module. This can be fed to your Arduino’s 5V pin to power it from the motors’ power supply. Don’t forget to connect Arduino GND to pin 5 on the module as well to complete the circuit.

Now you will need six digital output pins on your Arduino, two of which need to be PWM (pulse-width modulation) pins. PWM pins are denoted by the tilde (“~”) next to the pin number, for example:

Finally, connect the Arduino digital output pins to the driver module. In our example we have two DC motors, so digital pins D9, D8, D7 and D6 will be connected to pins IN1, IN2, IN3 and IN4 respectively. Then connect D10 to module pin 7 (remove the jumper first) and D5 to module pin 12 (again, remove the jumper).

The motor direction is controlled by sending a HIGH or LOW signal to the drive for each motor (or channel). For example for motor one, a HIGH to IN1 and a LOW to IN2 will cause it to turn in one direction, and  a LOW and HIGH will cause it to turn in the other direction.

However the motors will not turn until a HIGH is set to the enable pin (7 for motor one, 12 for motor two). And they can be turned off with a LOW to the same pin(s). However if you need to control the speed of the motors, the PWM signal from the digital pin connected to the enable pin can take care of it.

This is what we’ve done with the DC motor demonstration sketch. Two DC motors and an Arduino Uno are connected as described above, along with an external power supply. Then enter and upload the following sketch:

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH); 
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible 
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH); 
  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  } 
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  } 
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);  
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

So what’s happening in that sketch? In the function demoOne() we turn the motors on and run them at a PWM value of 200. This is not a speed value, instead power is applied for 200/255 of an amount of time at once.

Then after a moment the motors operate in the reverse direction (see how we changed the HIGHs and LOWs in thedigitalWrite() functions?).

To get an idea of the range of speed possible of your hardware, we run through the entire PWM range in the function demoTwo() which turns the motors on and them runs through PWM values zero to 255 and back to zero with the two for loops.

Finally this is demonstrated in the following video – using our well-worn tank chassis with two DC motors:

Controlling a Stepper Motor

Stepper motors may appear to be complex, but nothing could be further than the truth. In this example we control a typical NEMA-17 stepper motor that has four wires:

It has 200 steps per revolution, and can operate at at 60 RPM. If you don’t already have the step and speed value for your motor, find out now and you will need it for the sketch.

The key to successful stepper motor control is identifying the wires – that is which one is which. You will need to determine the A+, A-, B+ and B- wires. With our example motor these are red, green, yellow and blue. Now let’s get the wiring done.

Connect the A+, A-, B+ and B- wires from the stepper motor to the module connections 1, 2, 13 and 14 respectively. Place the jumpers included with the L298N module over the pairs at module points 7 and 12. Then connect the power supply as required to points 4 (positive) and 5 (negative/GND).

Once again if your stepper motor’s power supply is less than 12V, fit the jumper to the module at point 3 which gives you a neat 5V power supply for your Arduino.

Next, connect L298N module pins IN1, IN2, IN3 and IN4 to Arduino digital pins D8, D9, D10 and D11 respectively. Finally, connect Arduino GND to point 5 on the module, and Arduino 5V to point 6 if sourcing 5V from the module.

Controlling the stepper motor from your sketches is very simple, thanks to the Stepper Arduino library included with the Arduino IDE as standard.

To demonstrate your motor, simply load the stepper_oneRevolution sketch that is included with the Stepper library, for example:

Finally, check the value for

	const int stepsPerRevolution = 200;

in the sketch and change the 200 to the number of steps per revolution for your stepper motor, and also the speed which is preset to 60 RPM in the following line:

	myStepper.setSpeed(60);

Now you can save and upload the sketch, which will send your stepper motor around one revolution, then back again. This is achieved with the function

	myStepper.step(stepsPerRevolution); // for clockwise
	myStepper.step(-stepsPerRevolution); // for anti-clockwise

Finally, a quick demonstration of our test hardware is shown in the following video:

So there you have it, an easy an inexpensive way to control motors with your Arduino or compatible board. And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a fourth printing!) “Arduino Workshop”.

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 forum – dedicated to the projects and related items on this website.

Tronixstuff 25 Nov 11:54

Tutorial – L298N Dual Motor Controller Modules and Arduino

Learn how to use inexpensive L298N motor control modules to drive DC and stepper motors with Arduino. This is chapter fifty-nine of our huge Arduino tutorial series.

You don’t have to spend a lot of money to control motors with an Arduino or compatible board. After some hunting around we found a neat motor control module based on the L298N H-bridge IC that can allows you to control the speed and direction of two DC motors, or control one bipolar stepper motor with ease.

The L298N H-bridge module can be used with motors that have a voltage of between 5 and 35V DC. With the module used in this tutorial, there is also an onboard 5V regulator, so if your supply voltage is up to 12V you can also source 5V from the board.

So let’s get started!

First we’ll run through the connections, then explain how to control DC motors then a stepper motor. At this point, review the connections on the L298N H-bridge module.

Consider the following image – match the numbers against the list below the image:

  1. DC motor 1 “+” or stepper motor A+
  2. DC motor 1 “-” or stepper motor A-
  3. 12V jumper – remove this if using a supply voltage greater than 12V DC. This enables power to the onboard 5V regulator
  4. Connect your motor supply voltage here, maximum of 35V DC. Remove 12V jumper if >12V DC
  5. GND
  6. 5V output if 12V jumper in place, ideal for powering your Arduino (etc)
  7. DC motor 1 enable jumper. Leave this in place when using a stepper motor. Connect to PWM output for DC motor speed control.
  8. IN1
  9. IN2
  10. IN3
  11. IN4
  12. DC motor 2 enable jumper. Leave this in place when using a stepper motor. Connect to PWM output for DC motor speed control.
  13. DC motor 2 “+” or stepper motor B+
  14. DC motor 2 “-” or stepper motor B-

Controlling DC Motors

To control one or two DC motors is quite easy with the L298N H-bridge module. First connect each motor to the A and B connections on the L298N module. If you’re using two motors for a robot (etc) ensure that the polarity of the motors is the same on both inputs. Otherwise you may need to swap them over when you set both motors to forward and one goes backwards!

Next, connect your power supply – the positive to pin 4 on the module and negative/GND to pin 5. If you supply is up to 12V you can leave in the 12V jumper (point 3 in the image above) and 5V will be available from pin 6 on the module. This can be fed to your Arduino’s 5V pin to power it from the motors’ power supply. Don’t forget to connect Arduino GND to pin 5 on the module as well to complete the circuit.

Now you will need six digital output pins on your Arduino, two of which need to be PWM (pulse-width modulation) pins. PWM pins are denoted by the tilde (“~”) next to the pin number, for example:

Finally, connect the Arduino digital output pins to the driver module. In our example we have two DC motors, so digital pins D9, D8, D7 and D6 will be connected to pins IN1, IN2, IN3 and IN4 respectively. Then connect D10 to module pin 7 (remove the jumper first) and D5 to module pin 12 (again, remove the jumper).

The motor direction is controlled by sending a HIGH or LOW signal to the drive for each motor (or channel). For example for motor one, a HIGH to IN1 and a LOW to IN2 will cause it to turn in one direction, and  a LOW and HIGH will cause it to turn in the other direction.

However the motors will not turn until a HIGH is set to the enable pin (7 for motor one, 12 for motor two). And they can be turned off with a LOW to the same pin(s). However if you need to control the speed of the motors, the PWM signal from the digital pin connected to the enable pin can take care of it.

This is what we’ve done with the DC motor demonstration sketch. Two DC motors and an Arduino Uno are connected as described above, along with an external power supply. Then enter and upload the following sketch:

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;
void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH); 
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible 
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH); 
  // accelerate from zero to maximum speed
  for (int i = 0; i &lt; 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  } 
  // decelerate from maximum speed to zero
  for (int i = 255; i &gt;= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  } 
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);  
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

So what’s happening in that sketch? In the function demoOne() we turn the motors on and run them at a PWM value of 200. This is not a speed value, instead power is applied for 200/255 of an amount of time at once.

Then after a moment the motors operate in the reverse direction (see how we changed the HIGHs and LOWs in thedigitalWrite() functions?).

To get an idea of the range of speed possible of your hardware, we run through the entire PWM range in the function demoTwo() which turns the motors on and them runs through PWM values zero to 255 and back to zero with the two for loops.

Finally this is demonstrated in the following video – using our well-worn tank chassis with two DC motors:

Controlling a Stepper Motor

Stepper motors may appear to be complex, but nothing could be further than the truth. In this example we control a typical NEMA-17 stepper motor that has four wires:

It has 200 steps per revolution, and can operate at at 60 RPM. If you don’t already have the step and speed value for your motor, find out now and you will need it for the sketch.

The key to successful stepper motor control is identifying the wires – that is which one is which. You will need to determine the A+, A-, B+ and B- wires. With our example motor these are red, green, yellow and blue. Now let’s get the wiring done.

Connect the A+, A-, B+ and B- wires from the stepper motor to the module connections 1, 2, 13 and 14 respectively. Place the jumpers included with the L298N module over the pairs at module points 7 and 12. Then connect the power supply as required to points 4 (positive) and 5 (negative/GND).

Once again if your stepper motor’s power supply is less than 12V, fit the jumper to the module at point 3 which gives you a neat 5V power supply for your Arduino.

Next, connect L298N module pins IN1, IN2, IN3 and IN4 to Arduino digital pins D8, D9, D10 and D11 respectively. Finally, connect Arduino GND to point 5 on the module, and Arduino 5V to point 6 if sourcing 5V from the module.

Controlling the stepper motor from your sketches is very simple, thanks to the Stepper Arduino library included with the Arduino IDE as standard.

To demonstrate your motor, simply load the stepper_oneRevolution sketch that is included with the Stepper library, for example:

Finally, check the value for

const int stepsPerRevolution = 200;

in the sketch and change the 200 to the number of steps per revolution for your stepper motor, and also the speed which is preset to 60 RPM in the following line:

myStepper.setSpeed(60);

Now you can save and upload the sketch, which will send your stepper motor around one revolution, then back again. This is achieved with the function

myStepper.step(stepsPerRevolution); // for clockwise
	myStepper.step(-stepsPerRevolution); // for anti-clockwise

Finally, a quick demonstration of our test hardware is shown in the following video:

So there you have it, an easy an inexpensive way to control motors with your Arduino or compatible board. And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a fourth printing!) “Arduino Workshop”.

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 forum – dedicated to the projects and related items on this website.

The post Tutorial – L298N Dual Motor Controller Modules and Arduino appeared first on tronixstuff.

Tronixstuff 25 Nov 11:54

Tutorial – PCF8574 backpacks for LCD modules and Arduino

Learn how to use inexpensive serial backpacks with character LCD modules with your Arduino. This is chapter fifty-eight of our huge Arduino tutorial series.

Introduction

Using LCD modules with your Arduino is popular, however the amount of wiring requires time and patience to wire it up correctly – and also uses a lot of digital output pins. That’s why we love these serial backpack modules – they’re fitted to the back of your LCD module and allows connection to your Arduino (or other development board) with only four wires – power, GND, data and clock.

You can use this with LCD modules that have a HD44780-compatible interface with various screen sizes. For example a 16 x 2 module:

The backpack can also be used with 20 x 4 LCDs. The key is that your LCD must have the interface pads in a single row of sixteen, so it matches the pins on the backpack – for example:

Hardware Setup

Now let’s get started. First you need to solder the backpack to your LCD module. While your soldering iron is warming up, check that the backpack pins are straight and fit in the LCD module, for example:

Then solder in the first pin, while keeping the backpack flush with the LCD:

If it’s a bit crooked, you can reheat the solder and straighten it up again. Once you’re satisfied with the alignment, solder in the rest of the pins:

Now to keep things neat, trim off the excess header pins:

Once you’ve finished trimming the header pins, get four male to female jumper wires and connect the LCD module to your Arduino as shown in the following image and table. Then connect your Arduino to the computer via USB:

Software Setup

The next step is to download and install the Arduino I2C LCD library for use with the backpack. First of all, rename the “LiquidCrystal” library folder in your Arduino libraries folder. We do this just to keep it as a backup.

If you’re not sure where your library folder can be found – it’s usually in your sketchbook folder, whose location can usually be found in the Arduino IDE preferences menu:

Next, visit https://bitbucket.org/fmalpartida/new-liquidcrysta… and download the latest file, currently we’re using v1.2.1. Expanding the downloaded .zip file will reveal a new “LiquidCrystal” folder – copy this into your Arduino libraries folder.

Now restart the Arduino IDE if it was already running – or open it now. To test the module we have a demonstration sketch prepared, simply copy and upload the following sketch:

/* Demonstration sketch for PCF8574T I2C LCD Backpack 
Uses library from https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads GNU General Public License, version 3 (GPL-3.0) */
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C	lcd(0x27,2,1,0,4,5,6,7); // 0x27 is the I2C bus address for an unmodified backpack

void setup()
{
  // activate LCD module
  lcd.begin (16,2); // for 16 x 2 LCD module
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
}

void loop()
{
  lcd.home (); // set cursor to 0,0
  lcd.print(" tronixlabs.com"); 
  lcd.setCursor (0,1);        // go to start of 2nd line
  lcd.print(millis());
  delay(1000);
  lcd.setBacklight(LOW);      // Backlight off
  delay(250);
  lcd.setBacklight(HIGH);     // Backlight on
  delay(1000);
}

After a few moments the LCD will be initialised and start to display our URL and the value for millis, then blink the backlight off and on – for example:

If the text isn’t clear, or you just see white blocks – try adjusting the contrast using the potentiometer on the back of the module.

How to control the backpack in your sketch

As opposed to using the LCD module without the backpack, there’s a few extra lines of code to include in your sketches. To review these, open the example sketch mentioned earlier.

You will need the libraries as shown in lines 3, 4 and 5 – and initialise the module as shown in line 7. Note that the default I2C bus address is 0x27 – and the first parameter in the LiquidCrystal_I2C function.

Finally the three lines used in void setup() are also required to initialise the LCD. If you’re using a 20×4 LCD module, change the parameters in the lcd.begin() function.

From this point you can use all the standard LiquidCrystal functions such as lcd.setCursor() to move the cursor and lcd.write() to display text or variables as normal. The backlight can also be turned on and off with lcd.setBacklight(HIGH) or lcd.setBacklight(LOW).

You can permanently turn off the backlight by removing the physical jumper on the back of the module.

Changing the I2C bus address

If you want to use more than one module, or have another device on the I2C bus with address 0x27 then you’ll need to change the address used on the module. There are eight options to choose from, and these are selected by soldering over one or more of the following spots:

There are eight possible combinations, and these are described in Table 4 of the PCF8574 data sheet which can be downloaded from the NXP website. If you’re unsure about the bus address used by the module, simply connect it to your Arduino as described earlier and run the I2C scanner sketch from the Arduino playground.

We hope you enjoyed this tutorial and you can make use of it. Finally, if you enjoyed this tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a fourth printing!) “Arduino Workshop”.

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 forum – dedicated to the projects and related items on this website.
Tronixstuff 24 Sep 12:57

Tutorial – PCF8574 backpacks for LCD modules and Arduino

Learn how to use inexpensive serial backpacks with character LCD modules with your Arduino. This is chapter fifty-eight of our huge Arduino tutorial series.

Introduction

Using LCD modules with your Arduino is popular, however the amount of wiring requires time and patience to wire it up correctly – and also uses a lot of digital output pins. That’s why we love these serial backpack modules – they’re fitted to the back of your LCD module and allows connection to your Arduino (or other development board) with only four wires – power, GND, data and clock.

You can use this with LCD modules that have a HD44780-compatible interface with various screen sizes. For example a 16 x 2 module:

The backpack can also be used with 20 x 4 LCDs. The key is that your LCD must have the interface pads in a single row of sixteen, so it matches the pins on the backpack – for example:

Hardware Setup

Now let’s get started. First you need to solder the backpack to your LCD module. While your soldering iron is warming up, check that the backpack pins are straight and fit in the LCD module, for example:

Then solder in the first pin, while keeping the backpack flush with the LCD:

If it’s a bit crooked, you can reheat the solder and straighten it up again. Once you’re satisfied with the alignment, solder in the rest of the pins:

Now to keep things neat, trim off the excess header pins:

Once you’ve finished trimming the header pins, get four male to female jumper wires and connect the LCD module to your Arduino as shown in the following image and table. Then connect your Arduino to the computer via USB:

Software Setup

The next step is to download and install the Arduino I2C LCD library for use with the backpack. First of all, rename the “LiquidCrystal” library folder in your Arduino libraries folder. We do this just to keep it as a backup.

If you’re not sure where your library folder can be found – it’s usually in your sketchbook folder, whose location can usually be found in the Arduino IDE preferences menu:

Next, visit https://bitbucket.org/fmalpartida/new-liquidcrysta… and download the latest file, currently we’re using v1.2.1. Expanding the downloaded .zip file will reveal a new “LiquidCrystal” folder – copy this into your Arduino libraries folder.

Now restart the Arduino IDE if it was already running – or open it now. To test the module we have a demonstration sketch prepared, simply copy and upload the following sketch:

/* Demonstration sketch for PCF8574T I2C LCD Backpack 
Uses library from https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads GNU General Public License, version 3 (GPL-3.0) */
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C	lcd(0x27,2,1,0,4,5,6,7); // 0x27 is the I2C bus address for an unmodified backpack

void setup()
{
  // activate LCD module
  lcd.begin (16,2); // for 16 x 2 LCD module
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
}

void loop()
{
  lcd.home (); // set cursor to 0,0
  lcd.print(" tronixlabs.com"); 
  lcd.setCursor (0,1);        // go to start of 2nd line
  lcd.print(millis());
  delay(1000);
  lcd.setBacklight(LOW);      // Backlight off
  delay(250);
  lcd.setBacklight(HIGH);     // Backlight on
  delay(1000);
}

After a few moments the LCD will be initialised and start to display our URL and the value for millis, then blink the backlight off and on – for example:

If the text isn’t clear, or you just see white blocks – try adjusting the contrast using the potentiometer on the back of the module.

How to control the backpack in your sketch

As opposed to using the LCD module without the backpack, there’s a few extra lines of code to include in your sketches. To review these, open the example sketch mentioned earlier.

You will need the libraries as shown in lines 3, 4 and 5 – and initialise the module as shown in line 7. Note that the default I2C bus address is 0x27 – and the first parameter in the LiquidCrystal_I2C function.

Finally the three lines used in void setup() are also required to initialise the LCD. If you’re using a 20×4 LCD module, change the parameters in the lcd.begin() function.

From this point you can use all the standard LiquidCrystal functions such as lcd.setCursor() to move the cursor and lcd.write() to display text or variables as normal. The backlight can also be turned on and off with lcd.setBacklight(HIGH) or lcd.setBacklight(LOW).

You can permanently turn off the backlight by removing the physical jumper on the back of the module.

Changing the I2C bus address

If you want to use more than one module, or have another device on the I2C bus with address 0x27 then you’ll need to change the address used on the module. There are eight options to choose from, and these are selected by soldering over one or more of the following spots:

There are eight possible combinations, and these are described in Table 4 of the PCF8574 data sheet which can be downloaded from the NXP website. If you’re unsure about the bus address used by the module, simply connect it to your Arduino as described earlier and run the I2C scanner sketch from the Arduino playground.

We hope you enjoyed this tutorial and you can make use of it. Finally, if you enjoyed this tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a fourth printing!) “Arduino Workshop”.

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 forum – dedicated to the projects and related items on this website.

The post Tutorial – PCF8574 backpacks for LCD modules and Arduino appeared first on tronixstuff.

Tronixstuff 24 Sep 12:57

Project Review – Silicon Chip Capacitance Substitution Box

Introduction

Every month Australian electronics magazine Silicon Chip publishes a variety of projects, and in some cases various (well … one of two) electronics retailers will pick up the project and offer it as a kit. However for an increasing number of new projects they don’t, which leaves the interested reader with one option – build the entire project from scratch.

But thankfully this is no longer the case – as the team from Silicon Chip now offer a range of project PCBs and matching front panels for sale directly from their website. Although buying these parts is not the cheapest option, it gives the busy person who likes making things a quick start – or the inexperienced more opportunities to complete a successful project.

So as a test of this new service, I bought the PCB and front panel for the Capacitance Substitution Box project described by Nicholas Vinen in the Juily 2012 issue of SC:

This is something I’ve meant to make for a while – but didn’t really have the inclination to make one from scratch, so it was neat to see a version published in the magazine. I believe the subjects in the magazine article are oftern prototypes, which explains the difference in colour for the front panel.

The parts arrived in a week after placing the order, and are of a high quality:

When complete, the capacitance substitution box PCB and panel will fit nicely into an Altronics H0151 enclosure, so you don’t need to do any drilling or filing. The next task was to organise the required parts. The rotary switches, terminal posts and the usual odds and ends can be found at Altronics, Jaycar or other suppliers. However the main components – the capacitors – offered two options.

The first option is to simply use capacitors from personal stock or the stores. However the tolerance of these parts can vary wildly, with up to twenty percent either way. This is ok for simple uses, however when values are combined – the tolerance of larger values can negate the lower values completely. So instead I’ve chosen the second option – which involves using brand-name low-tolerance capacitors.

Thus I turned to element14 who stock not only a huge range of not only regular but also the low-tolerance capacitors, and can also have them on my desk usually by the next working day. Finally, it’s nice to have all the parts arrive in little bags… neatly organised ready to go:

It’s easy to search for low-tolerance parts with element14, as the automatic filtering has tolerance as a parameter:

Furthermore you can also ensure you have the voltage rating of at least 50V DC as well. So after half an hour the capacitor order was completed and arrived when expected – using parts from Panasonic, Vishay, and Wima. The tolerances of our capacitors used varied between one and ten percent, which will help improve the accuracy of the substitution box.

Assembly

The PCB has the capacitor values labelled neatly on the silk-screen, so soldering in all the capacitors was a relatively simple but long operation. Having them arrive in separate packets made life a lot easier. During the soldering process it’s a good idea to have a  break or two, which helps you avoid fatigue and making any mistakes.

There may be a few capacitors that are a little too wide to fit with the others, so they can be mounted on the other side of the PCB:

However they all end up fitting well:

The next step was to configure the first rotary switch for six position use, then cut the plastic stopped from the side of each rotary switch. In the following image you have a before and after example:

Now the rotary switches can have their shafts trimmed and then be soldered onto the PCB:

However ensure you have the first rotary switch in the right way – that is the selections are selected across the top half, not the bottom. Remove the nuts from the rotary switches, and double-check all the capacitors are fitted, as once the next step is completed … going back will be difficult to say the least.

At this point the banana sockets can be fitted to the panel, and then soldered into place, and then you’re finished. Just place the panel/PCB combination inside the box and screw it down:

Using the Capacitance Substitution Box

Does it work? Yes – however you don’t get exact values, there will always be a tolerance due to the original tolerance of the capacitors used and the stray capacitance of the wires between the box and the circuit (or capacitance meter). Nevertheless our example was quite successful. You can see the box in action with our Altronics LC meter kit in this video.

Again, using the best tolerance capacitors you can afford will increase the accuracy of this project.

Conclusion

Over time this would be a useful piece of equipment to have – so if your experiments or projects require varying capacitor value, this project will serve the purpose nicely. Plus it helps with mental arithmetic and measures of capacitance! Please do not ask me for copies of the entire Silicon Chip article, refusal may offend. Instead – visit their website for a reprint or digital access.

And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

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 forum – 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.

The post Project Review – Silicon Chip Capacitance Substitution Box appeared first on tronixstuff.

Add long-distance connectivity to your Arduino with the CATkit System

Introduction

Have you ever wanted to connect your Arduino to sensors or other devices but over a long distance? And we don’t mean a few metres – instead, distances of up to 100 metres? Doing so is possible with the CATkit system from SMART greenhouse.

This system is a combination of small boards that are connected between your Arduino and external devices using CAT5 networking cable, giving a very simple method of connecting devices over distances you previously thought may not have been possible – or have used costly wireless modules in the past.

The maximum distances possible depend on the signal type, for example:

  • analogue signals up to 100 metres (with a 0.125 V drop)
  • 1-wire signals (ideal for DS18B20 temperature sensors) up to 75 metres
  • SPI bus up to 50 metres
  • I2C bus up to 35 metres
  • Serial data at 9600 bps varies between 50 and 100 metres

In principle you could also use this with other development boards that utilise the Arduino Uno shield form-factor and work with 5V – so not for the Arduino Due, etc. For more information check out the .pdf documentation at the bottom of this page.

How it works

For each system you need one CATkit Arduino shield:

… and one or more Kitten boards. These are both inline – in that they can “tap in” to a run:

or have one RJ45 socket for installation at the end of a cable run:

Note that the inline Kitten has male pins for the breakout, and the end unit has females. These units are available in kit form or assembled. You then use the network cables between the shield and each Kitten, for example:

Each Kitten can distribute six signals, and up to three can be connected to one CATkit shield. These three distribute analogue pins 0~5, digital pins 0~5 and 6~11 respectively. You can also introduce external power to the CATkit shield and the onboard regulator will offer 5V at up to 950 mA for the power bus which can be accessed from the inline or end Kitten boards. This saves having to provide separate 5V power to devices away from the Arduino, and very convenient for sensors or remote I2C-interface displays.  

Using the CATkit system

If you have the units in kit form, assembly is very simple. For example – the main CATkit shield:

The shield is in the latest Arduino R3 format, and all the required parts are included. The PCB is neatly solder-masked and silk-screened so soldering is easy. The power regulator is in D-PAK form, however with a little help it’s easy to solder it in:

Otherwise the shield assembly is straight forward, and in around ten minutes you have the finished product (somehow we lost the DC socket, however one is included):

The cut-out in the PCB gives a neat clearance for the USB socket.  The inline unit was also easily assembled, and again the kit includes all the necessary parts:

… and after a few minutes of soldering the board is ready:

A benefit of using the kit version is that you can directly solder any wires from sensors straight to the PCB for more permanent installations. 

Using the CATkit system

Any Arduino user with a basic understanding of I/O will be ready for the CATkit system. You can think of it as a seamless extension to the required I/O pins, taking into account the maximum distances possible as noted on the CATkit website or earlier in this review.

For a quick test we connected an I2C-interface LCD using an inline Kitten module via 5M of network cable, as shown in this video.

Conclusion

With a little planning and the CATkit system you can create neat plug-and-play sensor or actuator networks with reusable lengths of common networking cable. To do so is simple – and it works, so for more information and distributors please visit the product website.

And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

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 forum – 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.

[Note – CATkit system parts are a promotional consideration from SMART green house]

The post Add long-distance connectivity to your Arduino with the CATkit System appeared first on tronixstuff.

Tronixstuff 12 Apr 23:33

Review – Intel Galileo Arduino-compatible Development Board

Introduction

Over the last year or two the rise of the single-board computer has captured the imagination and energy of many people, to the point where popular opinion has been that the Arduino world had been left behind. However this is far from the truth – there’s Arduino-compatible SBCs such as the pcDuino and now we have one from Intel  – the Intel Galileo.

Apparently the Galileo has been available in limited distribution for a few months, and now that the marketing machine has started up – we finally had the chance to order an Intel Galileo last week and now have one as the subject for this review. It’s our first look, based on information we could find at the time and some experimenting.

What’s in the box?

In the retail package we found the Intel Galileo itself:

… a diagram of what to do in the lid:

… and a universal AC to 5V 2A DC power supply with various fittings for different regions:

The only paper documentation was a safety and regulatory information booklet which gets recycled. We didn’t find a USB cable nor some stand-offs to lift the board off the bench a little.

Specifications

The Galileo is based a new chipset from Intel, the Quark SoC X1000 Application Processor, a 32-bit Intel Pentium-class system on a chip. For the uninitiated, the Galileo is a single-board computer running a small version of Linux that can somewhat emulate an Arduino Uno R3 in software. The hardware specifications are as such (from the Arduino website):

  • 400MHz 32-bit Intel® Pentium instruction set architecture (ISA)-compatible processor o 16 KBytes on-die L1 cache
    • 512 KBytes of on-die embedded SRAM
    • Simple to program: Single thread, single core, constant speed
    • ACPI compatible CPU sleep states supported
    • An integrated Real Time Clock (RTC), with an optional 3V “coin cell” battery for operation between turn on cycles.
  • 10/100 Ethernet connector
  • Full PCI Express* mini-card slot, with PCIe 2.0 compliant features
    • Works with half mini-PCIe cards with optional converter plate
    • Provides USB 2.0 Host Port at mini-PCIe connector
  • USB 2.0 Host connector
    • Support up to 128 USB end point devices
  • USB Device connector, used for programming
    • Beyond just a programming port – a fully compliant USB 2.0 Device controller
  • 10-pin Standard JTAG header for debugging
  • Reboot button to reboot the processor
  • Reset button to reset the sketch and any attached shields
  • Storage options:
    • Default – 8 MByte Legacy SPI Flash main purpose is to store the firmware (or bootloader) and the latest sketch. Between 256KByte and 512KByte is dedicated for sketch storage. The download will happen automatically from the development PC, so no action is required unless there is an upgrade that is being added to the firmware.
    • Default 512 KByte embedded SRAM, enabled by the firmware by default. No action required to use this feature.
    • Default 256 MByte DRAM, enabled by the firmware by default.
    • Optional micro SD card offers up to 32GByte of storage
    • USB storage works with any USB 2.0 compatible drive
    • 11 KByte EEPROM can be programmed via the EEPROM library.

However unlike other SBCs on the market – you don’t get any video or audio output.

Let’s have a quick look around the board. Here you can see the DC socket and microSD card socket:

 From the view below you can see the Arduino shield stacking headers and flash memory:

… more jumpers for settings, a USB host socket, USB connection (client) socket, RS232 via 3.5mm socket (!) and 10/100 Ethernet:

… and some nifty jumpers to select 3.3 or 5V operation for shields and IOREF:

… this jumper pair is to add a 3V battery to keep the real-time clock ticking over when the main supply is removed:

Perhaps a CR2032 button cell holder would be preferable, there’s plenty of room on the PCB. Finally – the two reset buttons:

If you want to reset your emulated Arduino, press the one on the left (labelled I). If you want to reboot the entire computer, press the one on the right (labelled X). This seems a little counter-intuitive, as you would imagine the button closer to the stacking headers would reset the Arduino. Note that if you reboot the computer, the last sketch you’ve uploaded will be removed and need to be uploaded again. Furthermore, more often than not rebooting the Galileo wasn’t entirely successful – and required a full removal of USB, power then replacing the power and USB to get another connection.

Turning the Galileo over reveals some fascinating PCB track patterns, and the mini-PCIe connector:

Getting Started

Having a slight bent towards Arduino, the first thing we like to do is get the blink sketch running. The documentation is scattered all over the place, so start from maker.intel.com and follow the links listed in the “Explore Intel makers” column. The closest thing to a quick setup guide can be downloaded hereThere’s a video by what sounds to be a ten year old explaining the board – who signs off by telling us it’s ok to break something (hopefully not the Galileo at $77 a pop). Marketing FTW. Eventually we found the official Intel support page for the Galileo, so bookmark that for future reference.

However if you just want to get started as quickly as possible, keep reading. First, download the Arduino IDE for Galileo from here. Next, extract the IDE folder to your root directory – and don’t have any spaces in the folder name. For example, use:

c:\GalileoIDE

and not:

C:\Arduino IDEs\galileo IDE\

Now plug in your Galileo – and always plug the 5V power into the Galileo before the USB (use the “USB client” socket). For Windows the USB driver (for “Gadget Serial v2.4”) is in the IDE folder, just point Windows to the top Galileo Arduino IDE folder.

Note that it takes around twenty seconds for the PC to recognise the Galileo via USB (as the Galileo needs time to boot up – it’s running Linux). For Windows users – after loading the IDE, check which COM port has been allocated. For some reason the Galileo can’t deal with COM10 or higher. To change this, head over to the Device Manager. Open Ports (COM & LPT) then right-click the Galileo and click properties:

Next, click the Port Settings tab, then Advanced:

Then select a free COM port number that’s under 10, close all the dialogue boxes and restart the computer. After the reboot, load the IDE, select the right board and serial port in the Tools menu – then select Firmware Update in the Help Menu. If for some reason you put a memory card in the microSD card slot – remove it before this process.

A confirmation box will appear, so move forward and wait for the process to finish. Don’t touch the IDE, board or anything near the Galileo until this finishes. Read some kit reviews. The update process took eight minutes for us, however will depend on the speed of your Internet connection.

Finally, try the ubiquitous blink sketch. Once uploaded,  the tiny LED next to the coin cell jumpers will blink as requested. Now we’ll explore more about using the Galileo as an Arduino-compatible board.

How Arduino-compatible is the Galileo?

The first thing we like to do with new boards that differ from the classic Uno is to run a speed test, and for this we use the following sketch by Steve Curd from the Arduino forum:

//
// Pi_2
//
// Steve Curd
// December 2012
//
// This program approximates pi utilizing the Newton's approximation.  It quickly
// converges on the first 5-6 digits of precision, but converges verrrry slowly
// after that.  For example, it takes over a million iterations to get to 7-8
// significant digits.
//
// I wrote this to evaluate the performance difference between the 8-bit Arduino Mega,
// and the 32-bit Arduino Due.
// 

#define ITERATIONS 100000L    // number of iterations
#define FLASH 1000            // blink LED every 1000 iterations

void setup() {
  pinMode(13, OUTPUT);        // set the LED up to blink every 1000 iterations
  Serial.begin(57600);
}

void loop() {

  unsigned long start, time;
  unsigned long niter=ITERATIONS;
  int LEDcounter = 0;
  boolean alternate = false;
  unsigned long i, count=0;
  float x = 1.0;
  float temp, pi=1.0;

  Serial.print("Beginning ");
  Serial.print(niter);
  Serial.println(" iterations...");
  Serial.println();

  start = millis();  
  for ( i = 2; i < niter; i++) {
    x *= -1.0;
    pi += x / (2.0f*(float)i-1.0f);
    if (LEDcounter++ > FLASH) {
      LEDcounter = 0;
      if (alternate) {
        digitalWrite(13, HIGH);
        alternate = false;
      } else {
        digitalWrite(13, LOW);
        alternate = true;
      }
      temp = 40000000.0 * pi;
    }
  }
  time = millis() - start;

  pi = pi * 4.0;

  Serial.print("# of trials = ");
  Serial.println(niter);
  Serial.print("Estimate of pi = ");
  Serial.println(pi, 10);

  Serial.print("Time: "); Serial.print(time); Serial.println(" ms");

  delay(10000);
}

It calculates Newton Approximation for pi using an infinite series. For comparison an Arduino Due takes 690 ms, an Arduino Mega 2560 takes 5765 ms, and a pcDuino v2 can do it in 9 to 43 ms (depending on what else is running on Linux). So out of the box, the Galileo takes 279 ms:

Out of the box there is 262144 bytes available for sketches. As the Arduino is emulated, the hardware for I/O is a little different than you may have expected, and provided by a variety of I2C port expanders, MUXs and so on. For example I2C can only run at 100 kHz in master mode, no slave mode, and similar restrictions on SPI as well. Again, review this page to learn more about the internal hardware differences between an Arduino Uno and Intel Galileo.

Visit this page and scroll down to the block diagram for a visual representation, and while you’re there – review the entire page to learn more about the specific Arduino Uno R3 implementation on the Galileo. A lot of work has been done to allow successful emulation of the Arduino using the Quark CPU and internal OS. For example the EEPROM library just works, and has 11264 bytes of storage.

You can get an idea of what is supported “out of the box” by reviewing the libraries included with the Galileo’s IDE installation, for example:

So most of the basic requirements are covered at the time of writing. And unlike some other SBCs emulating Arduino, the onboard Ethernet “just works” as it should with the Ethernet library – and the USBHost library can take advantage of the matching socket on the board. Again – research is the key, so spend some time determining if the Galileo can solve your problems.

One interesting example of the limitations of the “emulated” Arduino is the speed, and this has been highlighted by Al Williams of Dr Dobb’s journal – who ran a simple sketch to see how fast a digital output pin could be set. As GPIO is provided by external SPI- and I2C-based interface ICs, there will be a speed hit. But how much? Naturally we can’t use port manipulation so we’re back to simple digitalWrite functions with the following sketch:

int pin = 2;
boolean a = false;
void setup() 
{                
  pinMode(pin, OUTPUT);     
}

void loop() 
{
  digitalWrite(pin, a=!a);
}

An Arduino Uno running the sketch was clocked at 96.34 kHz:

… and the Intel Galileo was clocked at … 225.2 Hz:

This test isn’t a criticism of the Galileo, just an example of what you need to keep in mind when using it. If you’re curious about the real-time clock it’s accessed via Linux. Finally, there’s a list of known issues on the Intel forum – so check this out to get a grip on what is and is not working in terms of Arduino compatibility. One more thing – you will need a memory card installed if you want the Galileo to remember sketches after power-off.

Update – thanks to our friends (!) at reddit, you can push some I/O faster – see this post in the Intel forum.

Linux – internal

The Galileo arrived pre-loaded with a very light version of Linux, however due to the lack of video output you need to access the “computer” via some old-school methods. And thus one method is via Telnet over Ethernet. If you don’t have a Telnet client, try PuTTY. To get started, ensure you have your Galileo connected to power, client USB to PCm and to your LAN. Then upload the following sketch to your Galileo:

// https://communities.intel.com/message/213624
void setup()
{
  system("telnetd -l /bin/sh");
}

void loop()
{
  system("ifconfig eth0 > /dev/ttyGS0");
  sleep(10);
}

The observant will notice by using the system function you can send instructions to the Linux command line from your Arduino sketch. And any resulting output text can be sent to the serial monitor by directing it to ttyGS0.

Anyhow, the above sketch will run the ifconfig command and return relevant networking data about your Galileo – including its IP address:

Once you have the IP address, you can Telnet in and command your Galileo just like it’s 1992:

Don’t get too excited, there isn’t that much installed (e.g. no gcc or make). For more information on the Poky linux, visit the project page. Apart from running vi my *nix memory is a bit vague, however the onboard system is quite minimal. If you want to do anything serious, such as use a WiFi or other PCIe card – you’ll need to boot your Galileo with an external OS stored on a microSD card. Another way of looking at the Galileo is that it’s a board not for development with, but for running code built on a different system and then loaded onto the Galileo.

Linux – external

As I haven’t been a *nix user for a very long time, it didn’t seem worthwhile to spend a whole day preparing for an installing the external OS on the Galileo for review. However from what I can tell you’ll need to do this to run anything substantial including WiFi adaptors, python, node.js and so on. Which in my personal opinion sort of ruins the Galileo for me. Other SBCs can do all of this a lot easier, cheaper and with better documentation.

Arduino Support

As the Galileo is from Intel and not Arduino, you need to ask for support in the Intel forum. This will be an interesting test for Intel, will they invest in a substantial support effort or just stand back and say it’s all open source? Time will tell. In the meanwhile there is a gallery hosted by Intel with links to different projects.

Conclusion

Once again – remember that the Galileo is a limited single-board computer that emulates (to a certain, varying degree) an Arduino Uno R3. It is a contender if you need to integrate some Arduino-based control with software running on a light Linux machine, and all in a compact board. Or if you want to experiment with USB host and Ethernet on the Arduino platform at the same time, this could be a cheaper and more powerful option. Support is there if you can use Google, however this is not the idea beginners’ Arduino board. So don’t be a sheep and rush out and buy one after reading the marketing blurb – do your own research first.

Personally I would say that if you have a need for the specific hardware interfaces of the Galileo, and have a full understanding of the board limitations – then it’s the board for you. Otherwise if you want to experiment with a full single-board computer with Arduino compatibility, get a pcDuino. Full-sized images are available on flickr.

And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

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 forum – 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.

[Note – Intel Galileo purchased for review by tronixstuff.com and not a promotional consideration]

The post Review – Intel Galileo Arduino-compatible Development Board appeared first on tronixstuff.

Tronixstuff 12 Feb 03:59

Tutorial – Arduino and TFT Color Touch Screen

Learn how to use an inexpensive TFT colour  touch LCD shield with your Arduino. This is chapter twenty-nine of our huge Arduino tutorial series.

Updated 07/02/2014

There are many colour LCDs on the market that can be used with an Arduino, and in this tutorial we’ll explain how to use a model that is easy to use, has a touch screen, doesn’t waste all your digital output pins – and won’t break the bank. It’s the 2.8″ TFT colour touch screen shield from Tronixlabs:

And upside down:

As you can imagine, it completely covers an Arduino Uno or compatible board, and offers a neat way to create a large display or user-interface.  The display has a resolution of 320 x 240 pixels, supports up to 65536 colours and draws around 250mA of current from the Arduino’s internal 5V supply. 

And unlike other colour LCDs, this one doesn’t eat up all your digital output pins – it uses the SPI bus for the display (D10~D13), and four analogue pins (A0~A3) if you use the touch sensor. However if you also use the onboard microSD socket more pins will be required. 

With some imagination, existing Arduino knowledge and the explanation within you’ll be creating all sorts of displays and interfaces in a short period of time. Don’t be afraid to experiment!

Getting started

Setting up the hardware is easy – just plug the shield on your Arduino. Next, download the library bundle from here. Inside the .zip file is two folders – both which need to be copied into your …Arduino-1.0.xlibraries folder. Then you will need to rename the folder “TFT_Touch” to “TFT”. You will notice that the Arduino IDE already contains a library folder called TFT, so rename or move it.

Now let’s test the shield so you know it works, and also to have some quick fun. Upload the paint example included in the TFT library – then with a stylus or non-destructive pointer, you can select colour and draw on the LCD – as shown in this video. At this point we’d like to note that you should be careful with the screen – it doesn’t have a protective layer.

Afraid the quality of our camera doesn’t do the screen any justice, however the still image looks better:

Using the LCD 

Moving on, let’s start with using the display. In your sketches the following libraries need to be included using the following lines before void setup():

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

… and then the TFT library is initialised in void setup()

Tft.TFTinit();

Now you can use the various functions to display text and graphics. However you first need to understand how to define colours.

Defining colours

Functions with a colour parameter can accept one of the ten ten predefined colours – RED, GREEN, BLUE, BLACK, YELLOW, WHITE, CYAN, BRIGHT_RED, GRAY1 and GRAY2, or you can create your own colour value. Colours are defined with 16-but numbers in hexadecimal form, with 5 bits for red, 6 for green and 5 for blue – all packed together. For example – in binary:

MSB > RRRRRGGGGGGRRRRR < LSB

These are called RGB565-formatted numbers – and we use these in hexadecimal format with our display. So black will be all zeros, then converted to hexadecimal; white all ones, etc. The process of converting normal RGB values to RGB565 would give an aspirin a headache, but instead thanks to Henning Karlsen you can use his conversion tool to do the work for you. Consider giving Henning a donation for his efforts.

Displaying text

There are functions to display characters, strings of text, integers and float variables:

  Tft.drawChar(char, x, y, size, colour);          // displays single character variables
  Tft.drawString(string, x, y, size, colour);      // displays arrays of characters
  Tft.drawNumber(integer, x, y, size, colour);     // displays integers
  Tft.drawFloat(float, x, y, size, colour);        // displays floating-point numbers

In each of the functions, the first parameter is the variable or data to display; x and y are the coordinates of the top-left of the first character being displayed; and colour is either the predefined colour as explained previously, or the hexadecimal value for the colour you would like the text to be displayed in – e.g. 0xFFE0 is yellow.

The drawFloat() function is limited to two decimal places, however you can increase this if necessary. To do so, close the Arduino IDE if running, open the file TFTv2.cpp located in the TFT library folder – and search for the line:

INT8U decimal=2;

… then change the value to the number of decimal places you require. We have set ours to four with success, and the library will round out any more decimal places. To see these text display functions in action,  upload the following sketch:

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

char ascii = 'a';
char h1[] = "Hello";
char h2[] = "world";
float f1 = 3.12345678;

void setup()
{
  Tft.TFTinit(); 
}

void loop()
{
  Tft.drawNumber(12345678, 0, 0, 1, 0xF800);
  Tft.drawChar(ascii,0, 20,2, BLUE);
  Tft.drawString(h1,0, 50,3,YELLOW);
  Tft.drawString(h2,0, 90,4,RED);  
  Tft.drawFloat(f1, 4, 0, 140, 2, BLUE);      
}

… which should result in the following:

To clear the screen

To set the screen back to all black, use:

Tft.fillScreen();

Graphics functions

There are functions to draw individual pixels, circles, filled circles, lines, rectangles and filled rectangles. With these and a little planning you can create all sorts of images and diagrams. The functions are:

Tft.setPixel(x, y, COLOUR);                  
// set a pixel at x,y of colour COLOUR

Tft.drawLine(x1, y1, x2, y2, COLOUR);        
// draw a line from x1, y1 to x2, y2 of colour COLOUR

Tft.drawCircle(x, y, r, COLOUR);             
// draw a circle with centre at x, y and radius r of colour COLOUR

Tft.fillCircle(x, y, r, COLOUR);             
// draw a filled circle with centre at x, y and radius r of colour COLOUR

Tft.drawRectangle(x1, y1, x2, y2 ,COLOUR);   
// draw a rectangle from x1, y1 (top-left corner) to x2, y2 (bottom-right corner) of colour COLOUR

Tft.Tft.fillRectangle(x1, y1, x2, y2 ,COLOUR);   
// draw a filled rectangle from x1, y1 (top-left corner) to x2, y2 (bottom-right corner) of colour COLOUR

The following sketch demonstrates the functions listed above:

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

int x, y, x1, x2, y1, y2, r;

void setup()
{
  randomSeed(analogRead(0));
  Tft.TFTinit(); 
}
void loop()
{
  // random pixels
  for (int i=0; i<500; i++)
  {
    y=random(320);
    x=random(240);
    Tft.setPixel(x, y, YELLOW);
    delay(5);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random lines
  for (int i=0; i<50; i++)
  {
    y1=random(320);
    y2=random(320);    
    x1=random(240);
    x2=random(240);    
    Tft.drawLine(x1, y1, x2, y2, RED);   
    delay(10);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random circles
  for (int i=0; i<50; i++)
  {
    y=random(320);
    x=random(240);
    r=random(50);
    Tft.drawCircle(x, y, r, BLUE); 
    delay(10);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random filled circles
  for (int i=0; i<10; i++)
  {
    y=random(320);
    x=random(240);
    r=random(50);
    Tft.fillCircle(x, y, r, GREEN); 
    delay(250);
    Tft.fillCircle(x, y, r, BLACK);     
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random rectangles
  for (int i=0; i<50; i++)
  {
    y1=random(320);
    y2=random(320);    
    x1=random(240);
    x2=random(240);    
    Tft.drawRectangle(x1, y1, x2, y2, WHITE);   
    delay(10);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random filled rectangles
  for (int i=0; i<10; i++)
  {
    y1=random(320);
    y2=random(320);    
    x1=random(240);
    x2=random(240);    
    Tft.fillRectangle(x1, y1, x2, y2, RED);   
    delay(250);
    Tft.fillRectangle(x1, y1, x2, y2, BLACK);       
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen
}

… with the results shown in this video.

Using the touch screen

The touch screen operates in a similar manner to the other version documented earlier, in that it is a resistive touch screen and we very quickly apply voltage to one axis then measure the value with an analogue pin, then repeat the process for the other axis.

You can use the method in that chapter, however with our model you can use a touch screen library, and this is included with the library .zip file you downloaded at the start of this tutorial.

The library does simplify things somewhat, so without further ado upload the touchScreen example sketch included with the library. Open the serial monitor then start touching the screen. The coordinates of the area over a pixel being touch will be returned, along with the pressure – as shown in this video.

Take note of the pressure values, as these need to be considered when creating projects. If you don’t take pressure into account, there could be false positive touches detected which could cause mayhem in your project.

Now that you have a very simple method to determine the results of which part of the screen is being touched – you can create sketches to take action depending on the touch area. Recall from the example touch sketch that the x and y coordinates were mapped into the variables p.x and p.y, with the pressure mapped to p.z. You should experiment with your screen to determine which pressure values work for you.

In the following example, we don’t trigger a touch unless the pressure value p.z is greater than 300. Let’s create a simple touch-switch, with one half of the screen for ON and the other half for OFF. Here is the sketch:

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>
#include <TouchScreen.h> 

// determine the pins connected to the touch screen hardware
// A0~A3
#define YP A2   // must be an analog pin, use "An" notation!
#define XM A1   // must be an analog pin, use "An" notation!
#define YM 14   // can be a digital pin, this is A0
#define XP 17   // can be a digital pin, this is A3 

#define TS_MINX 116*2
#define TS_MAXX 890*2
#define TS_MINY 83*2
#define TS_MAXY 913*2

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// The 2.8" TFT Touch shield has 300 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM);

void setup() 
{
  Serial.begin(9600);
  Tft.TFTinit(); 
  Tft.fillScreen(); // clear screen
}

void loop() 
{
  // a point object holds x y and z coordinates
  Point p = ts.getPoint();
  p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
  p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320);
  Serial.println(p.y);
  if (p.y < 160 && p.z > 300) // top half of screen?
  {
    // off
    Tft.fillCircle(120, 160, 100, BLACK);     
    Tft.drawCircle(120, 160, 100, BLUE); 
  } else if (p.y >= 160 && p.z > 300)
  {
    // on
    Tft.fillCircle(120, 160, 100, BLUE); 
  }
}

What’s happening here? We divided the screen into two halves (well not physically…) and consider any touch with a y-value of less than 160 to be the off area, and the rest of the screen to be the on area. This is tested in the two if functions – which also use an and (“&&”) to check the pressure. If the pressure is over 300 (remember, this could be different for you) – the touch is real and the switch is turned on or off.

… and a quick demonstration video of this in action.

Displaying images from a memory card

We feel this warrants a separate tutorial, however if you can’t wait – check out the demo sketch which includes some example image files to use.

Conclusion

By now I hope you have the answer to “how do you use a touch screen LCD with Arduino?” and had some fun learning with us. You can get your LCD from Tronixlabs. And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

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 forum – 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.

Tutorial – Arduino and TFT Color Touch Screen

Learn how to use an inexpensive TFT colour  touch LCD shield with your Arduino. This is chapter twenty-nine of our huge Arduino tutorial series.

Updated 07/02/2014

There are many colour LCDs on the market that can be used with an Arduino, and in this tutorial we’ll explain how to use a model that is easy to use, has a touch screen, doesn’t waste all your digital output pins – and won’t break the bank. It’s the 2.8″ TFT colour touch screen shield from Tronixlabs:

And upside down:

As you can imagine, it completely covers an Arduino Uno or compatible board, and offers a neat way to create a large display or user-interface.  The display has a resolution of 320 x 240 pixels, supports up to 65536 colours and draws around 250mA of current from the Arduino’s internal 5V supply. 

And unlike other colour LCDs, this one doesn’t eat up all your digital output pins – it uses the SPI bus for the display (D10~D13), and four analogue pins (A0~A3) if you use the touch sensor. However if you also use the onboard microSD socket more pins will be required. 

With some imagination, existing Arduino knowledge and the explanation within you’ll be creating all sorts of displays and interfaces in a short period of time. Don’t be afraid to experiment!

Getting started

Setting up the hardware is easy – just plug the shield on your Arduino. Next, download the library bundle from here. Inside the .zip file is two folders – both which need to be copied into your …\Arduino-1.0.x\libraries folder. Then you will need to rename the folder “TFT_Touch” to “TFT”. You will notice that the Arduino IDE already contains a library folder called TFT, so rename or move it.

Now let’s test the shield so you know it works, and also to have some quick fun. Upload the paint example included in the TFT library – then with a stylus or non-destructive pointer, you can select colour and draw on the LCD – as shown in this video. At this point we’d like to note that you should be careful with the screen – it doesn’t have a protective layer.

Afraid the quality of our camera doesn’t do the screen any justice, however the still image looks better:

Using the LCD 

Moving on, let’s start with using the display. In your sketches the following libraries need to be included using the following lines before void setup():

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

… and then the TFT library is initialised in void setup()

Tft.TFTinit();

Now you can use the various functions to display text and graphics. However you first need to understand how to define colours.

Defining colours

Functions with a colour parameter can accept one of the ten ten predefined colours – RED, GREEN, BLUE, BLACK, YELLOW, WHITE, CYAN, BRIGHT_RED, GRAY1 and GRAY2, or you can create your own colour value. Colours are defined with 16-but numbers in hexadecimal form, with 5 bits for red, 6 for green and 5 for blue – all packed together. For example – in binary:

MSB > RRRRRGGGGGGRRRRR < LSB

These are called RGB565-formatted numbers – and we use these in hexadecimal format with our display. So black will be all zeros, then converted to hexadecimal; white all ones, etc. The process of converting normal RGB values to RGB565 would give an aspirin a headache, but instead thanks to Henning Karlsen you can use his conversion tool to do the work for you. Consider giving Henning a donation for his efforts.

Displaying text

There are functions to display characters, strings of text, integers and float variables:

Tft.drawChar(char, x, y, size, colour);          // displays single character variables
  Tft.drawString(string, x, y, size, colour);      // displays arrays of characters
  Tft.drawNumber(integer, x, y, size, colour);     // displays integers
  Tft.drawFloat(float, x, y, size, colour);        // displays floating-point numbers

In each of the functions, the first parameter is the variable or data to display; x and y are the coordinates of the top-left of the first character being displayed; and colour is either the predefined colour as explained previously, or the hexadecimal value for the colour you would like the text to be displayed in – e.g. 0xFFE0 is yellow.

The drawFloat() function is limited to two decimal places, however you can increase this if necessary. To do so, close the Arduino IDE if running, open the file TFTv2.cpp located in the TFT library folder – and search for the line:

INT8U decimal=2;

… then change the value to the number of decimal places you require. We have set ours to four with success, and the library will round out any more decimal places. To see these text display functions in action,  upload the following sketch:

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

char ascii = 'a';
char h1[] = "Hello";
char h2[] = "world";
float f1 = 3.12345678;

void setup()
{
  Tft.TFTinit(); 
}

void loop()
{
  Tft.drawNumber(12345678, 0, 0, 1, 0xF800);
  Tft.drawChar(ascii,0, 20,2, BLUE);
  Tft.drawString(h1,0, 50,3,YELLOW);
  Tft.drawString(h2,0, 90,4,RED);  
  Tft.drawFloat(f1, 4, 0, 140, 2, BLUE);      
}

… which should result in the following:

To clear the screen

To set the screen back to all black, use:

Tft.fillScreen();

Graphics functions

There are functions to draw individual pixels, circles, filled circles, lines, rectangles and filled rectangles. With these and a little planning you can create all sorts of images and diagrams. The functions are:

Tft.setPixel(x, y, COLOUR);                  
// set a pixel at x,y of colour COLOUR

Tft.drawLine(x1, y1, x2, y2, COLOUR);        
// draw a line from x1, y1 to x2, y2 of colour COLOUR

Tft.drawCircle(x, y, r, COLOUR);             
// draw a circle with centre at x, y and radius r of colour COLOUR

Tft.fillCircle(x, y, r, COLOUR);             
// draw a filled circle with centre at x, y and radius r of colour COLOUR

Tft.drawRectangle(x1, y1, x2, y2 ,COLOUR);   
// draw a rectangle from x1, y1 (top-left corner) to x2, y2 (bottom-right corner) of colour COLOUR

Tft.Tft.fillRectangle(x1, y1, x2, y2 ,COLOUR);   
// draw a filled rectangle from x1, y1 (top-left corner) to x2, y2 (bottom-right corner) of colour COLOUR

The following sketch demonstrates the functions listed above:

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

int x, y, x1, x2, y1, y2, r;

void setup()
{
  randomSeed(analogRead(0));
  Tft.TFTinit(); 
}
void loop()
{
  // random pixels
  for (int i=0; i<500; i++)
  {
    y=random(320);
    x=random(240);
    Tft.setPixel(x, y, YELLOW);
    delay(5);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random lines
  for (int i=0; i<50; i++)
  {
    y1=random(320);
    y2=random(320);    
    x1=random(240);
    x2=random(240);    
    Tft.drawLine(x1, y1, x2, y2, RED);   
    delay(10);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random circles
  for (int i=0; i<50; i++)
  {
    y=random(320);
    x=random(240);
    r=random(50);
    Tft.drawCircle(x, y, r, BLUE); 
    delay(10);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random filled circles
  for (int i=0; i<10; i++)
  {
    y=random(320);
    x=random(240);
    r=random(50);
    Tft.fillCircle(x, y, r, GREEN); 
    delay(250);
    Tft.fillCircle(x, y, r, BLACK);     
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random rectangles
  for (int i=0; i<50; i++)
  {
    y1=random(320);
    y2=random(320);    
    x1=random(240);
    x2=random(240);    
    Tft.drawRectangle(x1, y1, x2, y2, WHITE);   
    delay(10);
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen

    // random filled rectangles
  for (int i=0; i<10; i++)
  {
    y1=random(320);
    y2=random(320);    
    x1=random(240);
    x2=random(240);    
    Tft.fillRectangle(x1, y1, x2, y2, RED);   
    delay(250);
    Tft.fillRectangle(x1, y1, x2, y2, BLACK);       
  }
  delay(1000); 
  Tft.fillScreen(); // clear screen
}

… with the results shown in this video.

Using the touch screen

The touch screen operates in a similar manner to the other version documented earlier, in that it is a resistive touch screen and we very quickly apply voltage to one axis then measure the value with an analogue pin, then repeat the process for the other axis.

You can use the method in that chapter, however with our model you can use a touch screen library, and this is included with the library .zip file you downloaded at the start of this tutorial.

The library does simplify things somewhat, so without further ado upload the touchScreen example sketch included with the library. Open the serial monitor then start touching the screen. The coordinates of the area over a pixel being touch will be returned, along with the pressure – as shown in this video.

Take note of the pressure values, as these need to be considered when creating projects. If you don’t take pressure into account, there could be false positive touches detected which could cause mayhem in your project.

Now that you have a very simple method to determine the results of which part of the screen is being touched – you can create sketches to take action depending on the touch area. Recall from the example touch sketch that the x and y coordinates were mapped into the variables p.x and p.y, with the pressure mapped to p.z. You should experiment with your screen to determine which pressure values work for you.

In the following example, we don’t trigger a touch unless the pressure value p.z is greater than 300. Let’s create a simple touch-switch, with one half of the screen for ON and the other half for OFF. Here is the sketch:

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>
#include <TouchScreen.h> 

// determine the pins connected to the touch screen hardware
// A0~A3
#define YP A2   // must be an analog pin, use "An" notation!
#define XM A1   // must be an analog pin, use "An" notation!
#define YM 14   // can be a digital pin, this is A0
#define XP 17   // can be a digital pin, this is A3 

#define TS_MINX 116*2
#define TS_MAXX 890*2
#define TS_MINY 83*2
#define TS_MAXY 913*2

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// The 2.8" TFT Touch shield has 300 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM);

void setup() 
{
  Serial.begin(9600);
  Tft.TFTinit(); 
  Tft.fillScreen(); // clear screen
}

void loop() 
{
  // a point object holds x y and z coordinates
  Point p = ts.getPoint();
  p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
  p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320);
  Serial.println(p.y);
  if (p.y < 160 && p.z > 300) // top half of screen?
  {
    // off
    Tft.fillCircle(120, 160, 100, BLACK);     
    Tft.drawCircle(120, 160, 100, BLUE); 
  } else if (p.y >= 160 && p.z > 300)
  {
    // on
    Tft.fillCircle(120, 160, 100, BLUE); 
  }
}

What’s happening here? We divided the screen into two halves (well not physically…) and consider any touch with a y-value of less than 160 to be the off area, and the rest of the screen to be the on area. This is tested in the two if functions – which also use an and (“&&”) to check the pressure. If the pressure is over 300 (remember, this could be different for you) – the touch is real and the switch is turned on or off.

… and a quick demonstration video of this in action.

Displaying images from a memory card

We feel this warrants a separate tutorial, however if you can’t wait – check out the demo sketch which includes some example image files to use.

Conclusion

By now I hope you have the answer to “how do you use a touch screen LCD with Arduino?” and had some fun learning with us. You can get your LCD from Tronixlabs. And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

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 forum – 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.

The post Tutorial – Arduino and TFT Color Touch Screen appeared first on tronixstuff.

Tutorial – Arduino and Color LCD

Learn how to use an inexpensive colour LCD shield with your Arduino. This is chapter twenty-eight of our huge Arduino tutorial series.

Updated 03/02/2014

There are many colour LCDs on the market that can be used with an Arduino, and for this tutorial we’re using a relatively simple model available that is available from suppliers such as Tronixlabs, based on a small LCD originally used in Nokia 6100 mobile phones:

These are a convenient and inexpensive way of displaying data, or for monitoring variables when debugging a sketch. Before getting started, a small amount of work is required.

From the two examples we have seen, neither of them arrive fitted with stacking headers (or in Sparkfun’s case – not included) or pins, so before doing anything you’ll need to fit your choice of connector. Although the LCD shield arrived with stacking headers, we used in-line pins as another shield would never be placed on top:

Which can easily be soldered to the shield in a few minutes:

 While we’re on the subject of pins – this shield uses D3~D5 for the three buttons, and D8, 9, 11 and 13 for the LCD interface. The shield takes 5V and doesn’t require any external power for the backlight. The LCD module has a resolution of 128 x 128 pixels, with nine defined colours (red, green, blue, cyan, magenta, yellow, brown, orange, pink) as well as black and white.

So let’s get started. From a software perspective, the first thing to do is download and install the library for the LCD shield. Visit the library page here. Then download the .zip file, extract and copy the resulting folder into your ..arduino-1.0.xlibraries folder. Be sure to rename the folder to “ColorLCDShield“. Then restart the Arduino IDE if it was already open.

At this point let’s check the shield is working before moving forward. Once fitted to your Arduino, upload the ChronoLCD_Color sketch that’s included with the library, from the IDE Examples menu:

This will result with a neat analogue clock you can adjust with the buttons on the shield, as shown in this video.

It’s difficult to photograph the LCD – (some of them have very bright backlights), so the image may not be a true reflection of reality. Nevertheless this shield is easy to use and we will prove this in the following examples. So how do you control the color LCD shield in your sketches?

At the start of every sketch, you will need the following lines:

#include "ColorLCDShield.h"
LCDShield lcd;

as well as the following in void setup():

lcd.init(PHILIPS); 
lcd.contrast(63); // sets LCD contrast (value between 0~63)

With regards to lcd.init(), try it first without a parameter. If the screen doesn’t work, try EPSON instead. There are two versions of the LCD shield floating about each with a different controller chip. The contrast parameter is subjective, however 63 looks good – but test for yourself.

Now let’s move on to examine each function with a small example, then use the LCD shield in more complex applications.

The LCD can display 8 rows of 16 characters of text. The function to display text is:

lcd.setStr("text", y,x, foreground colour, background colour);

where x and y are the coordinates of the top left pixel of the first character in the string. Another necessary function is:

lcd.clear(colour);

Which clears the screen and sets the background colour to the parameter colour.  Please note – when referring to the X- and Y-axis in this article, they are relative to the LCD in the position shown below. Now for an example – to recreate the following display:

… use the following sketch:

// Example 28.1
#include "ColorLCDShield.h"
LCDShield lcd;

void setup()
{
 // following two required for LCD
 lcd.init(PHILIPS); 
 lcd.contrast(63); // sets LCD contrast (value between 0~63)
}

void loop()
{
 lcd.clear(BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 0,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 15,2, WHITE, BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 30,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 45,2, WHITE, BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 60,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 75,2, WHITE, BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 90,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 105,2, WHITE, BLACK);
 do {} while (1>0);
}

In example 28.1 we used the function lcd.clear(), which unsurprisingly cleared the screen and set the background a certain colour.

Let’s have a look at the various background colours in the following example. The lcd.clear()  function is helpful as it can set the entire screen area to a particular colour. As mentioned earlier, there are the predefined colours red, green, blue, cyan, magenta, yellow, brown, orange, pink, as well as black and white. Here they are in the following example:

// Example 28.2

int del = 1000;
#include "ColorLCDShield.h"
LCDShield lcd; 
void setup() 
{ 
  // following two required for LCD 
  lcd.init(PHILIPS); 
  lcd.contrast(63); // sets LCD contrast (value between 0~63) 
}

void loop()
{
 lcd.clear(WHITE);
 lcd.setStr("White", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(BLACK);
 lcd.setStr("Black", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(YELLOW);
 lcd.setStr("Yellow", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(PINK);
 lcd.setStr("Pink", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(MAGENTA);
 lcd.setStr("Magenta", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(CYAN);
 lcd.setStr("Cyan", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(BROWN);
 lcd.setStr("Brown", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(ORANGE);
 lcd.setStr("Orange", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(BLUE);
 lcd.setStr("Blue", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(RED);
 lcd.setStr("Red", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(GREEN);
 lcd.setStr("Green", 39,40, WHITE, BLACK);
 delay(del);
}

And now to see it in action. In this demonstration video the colours are more livid in real life, unfortunately the camera does not capture them so well.

 

Now that we have had some experience with the LCD library’s functions, we can move on to drawing some graphical objects. Recall that the screen has a resolution of 128 by 128 pixels. We have four functions to make use of this LCD real estate, so let’s see how they work. The first is:

lcd.setPixel(int colour, Y, X);

This function places a pixel (one LCD dot) at location x, y with the colour of colour.

Note – in this (and all the functions that have a colour parameter) you can substitute the colour (e.g. BLACK) for a 12-bit RGB value representing the colour required. Next is:

lcd.setLine(x0, y0, x1, y1, COLOUR);

Which draws a line of colour COLOUR, from position x0, y0 to x1, y1. Our next function is:

lcd.setRect(x0, y0, x1, y1, fill, COLOUR);

This function draws an oblong or square of colour COLOUR with the top-left point at x0, y0 and the bottom right at x1, y1. Fill is set to 0 for an outline, and 1 for a filled oblong. It would be convenient for drawing bar graphs for data representation. And finally, we can also create circles, using:

lcd.setCircle(x, y, radius, COLOUR);

X and Y is the location for the centre of the circle, radius and COLOUR are self-explanatory. We will now use these graphical functions in the following demonstration sketch:

// Example 28.3

#include "ColorLCDShield.h"
LCDShield lcd;
int del = 1000;
int xx, yy = 0;

void setup()
{
  lcd.init(PHILIPS); 
  lcd.contrast(63); // sets LCD contrast (value between 0~63)
  lcd.clear(BLACK);
  randomSeed(analogRead(0));
}

void loop()
{
  lcd.setStr("Graphic Function", 40,3, WHITE, BLACK);
  lcd.setStr("Test Sketch", 55, 20, WHITE, BLACK); 
  delay(5000);
  lcd.clear(BLACK);
  lcd.setStr("lcd.setPixel", 40,20, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK);
  for (int a=0; a<500; a++)
  {
    xx=random(160);
    yy=random(160);
    lcd.setPixel(WHITE, yy, xx);
    delay(10);
  }
  delay(del);
  lcd.clear(BLACK);
  lcd.setStr("LCDDrawCircle", 40,10, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK); 
  for (int a=0; a<2; a++)
  {
    for (int b=1; b<6; b++)
    {
      xx=b*5;
      lcd.setCircle(32, 32, xx, WHITE);
      delay(200);
      lcd.setCircle(32, 32, xx, BLACK);
      delay(200);
    }
  }
  lcd.clear(BLACK); 
  for (int a=0; a<3; a++)
  {
    for (int b=1; b<12; b++)
    {
      xx=b*5;
      lcd.setCircle(32, 32, xx, WHITE);
      delay(100);
    }
    lcd.clear(BLACK);
  }
  lcd.clear(BLACK); 
  for (int a=0; a<3; a++)
  {
    for (int b=1; b<12; b++)
    {
      xx=b*5;
      lcd.setCircle(32, 32, xx, WHITE);
      delay(100);
    }
    lcd.clear(BLACK);
  }
  delay(del);
  lcd.clear(BLACK);
  lcd.setStr("LCDSetLine", 40,10, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK); 
  for (int a=0; a<160; a++)
  {
    xx=random(160);
    lcd.setLine(a, 1, xx, a, WHITE);
    delay(10);
  }
  lcd.clear(BLACK);
  lcd.setStr("LCDSetRect", 40,10, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK); 
  for (int a=0; a<10; a++)
  {
    lcd.setRect(32,32,64,64,0,WHITE);
    delay(200);
    lcd.clear(BLACK);
    lcd.setRect(32,32,64,64,1,WHITE);
    delay(200);
    lcd.clear(BLACK); 
  }
  lcd.clear(BLACK); 
}

The results of this sketch are shown in this video. For photographic reasons, I will stick with white on black for the colours.

So now you have an explanation of the functions to drive the screen – and only your imagination is holding you back.

Conclusion

Hopefully this tutorial is of use to you. and you’re no longer wondering “how to use a color LCD with Arduino”. They’re available from our tronixlabs store. And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

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 forum – 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.