Tag Archive | "LCD"

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

Arduino TFT colour touch shield front

And upside down:

Arduino TFT colour touch shield back

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:

Arduino TFT colour touch shield paint demonstration

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

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

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:

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:

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:

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

… which should result in the following:

Arduino TFT colour touch shield text

To clear the screen

To set the screen back to all black, use:

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:

The following sketch demonstrates the functions listed above:

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

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. And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book “Arduino Workshop” from No Starch Press. Finally, thanks to Linksprite for their support.

 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.

Posted in arduino, LCD, Linksprite, TFT, touch screen, tronixstuff, tutorial

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 Linksprite (and previously Sparkfun), based on a small LCD originally used in Nokia 6100 mobile phones:

Arduino Color LCD shield

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 Linksprite shield arrived with stacking headers, we used in-line pins as another shield would never be placed on top:

Arduino Color LCD shield fit headers

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

Arduino Color LCD shield fitted

 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.x\libraries 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:

Arduino Color LCD shield example sketch

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:

as well as the following in void setup():

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:

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

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:

Arduino Color LCD shield text demonstration

… use the following sketch:

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:

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:

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:

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

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:


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:

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”. We also have another tutorial using larged ILI9325 modules, which are larged and have a clearer display (they’re TFT LCDs) but can be a little trickier.

And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book “Arduino Workshop” from No Starch Press.

 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.

Posted in arduino, LCD, LCD-09363, Linksprite, SHD_LCD_NOKIA, sparkfun, tronixstuff, tutorialComments (0)

Tutorial – Arduino and ILI9325 colour TFT LCD modules

Learn how to use inexpensive ILI9325 colour TFT LCD modules in chapter fifty 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.

Introduction

Colour TFT LCD modules just keep getting cheaper, so in this tutorial we’ll show you how to get going with some of the most inexpensive modules we could find. The subject of our tutorial is a 2.8″ 240 x 320 TFT module with the ILI9325 LCD controller chip. If you look in ebay this example should appear pretty easily, here’s a photo of the front and back to help identify it:

There is also the line “HY-TFT240_262k HEYAODZ110510″ printed on the back of the module. They should cost less than US$10 plus shipping. Build quality may not be job number one at the factory so order a few, however considering the cost of something similar from other retailers it’s cheap insurance. You’ll also want sixteen male to female jumper wires to connect the module to your Arduino.

Getting started

To make life easier we’ll use an Arduino library “UTFT” written for this and other LCD modules. It has been created by Henning Karlsen and can be downloaded from his website. If you can, send him a donation – this library is well worth it. Once you’ve downloaded and installed the UTFT library, the next step is to wire up the LCD for a test.

Run a jumper from the following LCD module pins to your Arduino Uno (or compatible):

  • DB0 to DB7 > Arduino D0 to D7 respectively
  • RD > 3.3 V
  • RSET > A2
  • CS > A3
  • RW > A4
  • RS > A5
  • backlight 5V > 5V
  • backlight GND > GND

Then upload the following sketch – Example 50.1. You should be presented with the following on your display:

If you’re curious, the LCD module and my Eleven board draws 225 mA of current. If that didn’t work for you, double-check the wiring against the list provided earlier. Now we’ll move forward and learn how to display text and graphics.

Sketch preparation

You will always need the following before void setup():

and in void setup():

with the former command, change orientation to either LANDSCAPE to PORTRAIT depending on how you’ll view the screen. You may need further commands however these are specific to features that will be described below. The function .clrScr() will clear the screen.

Displaying Text

There are three different fonts available with the library. To use them add the following three lines before void setup():

When displaying text you’ll need to define the foreground and background colours with the following:

Where red, green and blue are values between zero and 255. So if you want white use 255,255,255 etc. For some named colours and their RGB values, click here. To select the required font, use one of the following:

Now to display the text use the function:

where text is what you’d like to display, x is the horizontal alignment (LEFT, CENTER, RIGHT) or position in pixels from the left-hand side of the screen and y is the starting point of the top-left of the text. For example, to start at the top-left of the display y would be zero. You can also display a string variable instead of text in inverted commas.

You can see all this in action with the following sketch – Example 50.2, which is demonstrated in the following video:

Furthremore, you can also specify the angle of display, which gives a simple way of displaying text on different slopes. Simply add the angle as an extra parameter at the end:

Again, see the following sketch – Example 50.2a, and the results below:

Displaying Numbers

Although you can display numbers with the text functions explained previously, there are two functions specifically for displaying integers and floats.

You can see these functions in action with the following sketch – Example 50.3, with an example of the results below:

example50p3

Displaying Graphics

There’s a few graphic functions that can be used to create required images. The first is:.

which is used the fill the screen with a certain colour. The next simply draws a pixel at a specified x,y location:

Remember that the top-left of the screen is 0,0. Moving on, to draw a single line, use:

where the line starts at x1,y1 and finishes at x2,y2. Need a rectangle? Use:

where the top-left of the rectangle is x1,y1 and the bottom-right is x2, y2. You can also have rectangles with rounded corners, just use:

instead. And finally, circles – which are quite easy. Just use:

where x,y are the coordinates for the centre of the circle, and r is the radius. For a quick demonstration of all the graphic functions mentioned so far, see Example 50.4 – and the following video:

Displaying bitmap images

If you already have an image in .gif, .jpg or .png format that’s less than 300 KB in size, this can be displayed on the LCD. To do so, the file needs to be converted to an array which is inserted into your sketch. Let’s work with a simple example to explain the process. Below is our example image:

jrt3030

Save the image of the puppy somewhere convenient, then visit this page. Select the downloaded file, and select the .c and Arduino radio buttons, then click “make file”. After a moment or two a new file will start downloading. When it arrives, open it with a text editor – you’ll see it contains a huge array and another #include statement – for example:

cfile

Past the #include statement and the array into your sketch above void setup(). After doing that, don’t be tempted to “autoformat” the sketch in the Arduino IDE. Now you can use the following function to display the bitmap on the LCD:

Where x and y are the top-left coordinates of the image, width and height are the … width and height of the image, and name is the name of the array. Scale is optional – you can double the size of the image with this parameter. For example a value of two will double the size, three triples it – etc. The function uses simple interpolation to enlarge the image, and can be a clever way of displaying larger images without using extra memory. Finally, you can also display the bitmap on an angle – using:

where angle is the angle of rotation and cx/cy are the coordinates for the rotational centre of the image.

The bitmap functions using the example image have been used in the following sketch – Example 50.5, with the results in the following video:

Unfortunately the camera doesn’t really do the screen justice, it looks much better with the naked eye.

What about the SD card socket and touch screen?

The SD socket didn’t work, and I won’t be working with the touch screen at this time.

Conclusion

So there you have it – an incredibly inexpensive and possibly useful LCD module. Thank you to Henning Karlsen for his useful library, and if you found it useful – send him a donation via his page.

LEDborder

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.

Posted in arduino, bitmap, display, ILI9325, LCD, lesson, mega, TFT, tronixstuff, tutorialComments (57)

Arduino and KTM-S1201 LCD modules

Learn how to use very inexpensive KTM-S1201 LCD modules in this edition of our Arduino tutorials. This is chapter forty-nine 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.

Introduction

After looking for some displays to use with another (!) clock, I came across some 12-digit numeric LCD displays. They aren’t anything flash, and don’t have a back light –  however they were one dollar each. How could you say no to that? So I ordered a dozen to try out. The purpose of this tutorial is to show you how they are used with an Arduino in the simplest manner possible.

Moving forward – the modules look like OEM modules for desktop office phones from the 1990s:

With a quick search on the Internet you will find a few sellers offering them for a dollar each. The modules (data sheet) use the NEC PD7225 controller IC (data sheet):

They aren’t difficult to use, so I’ll run through set up and operation with a few examples.

Hardware setup

First you’ll need to solder some sort of connection to the module – such as 2×5 header pins. This makes it easy to wire it up to a breadboard or a ribbon cable:

The rest of the circuitry is straight-forward. There are ten pins in two rows of five, and with the display horizontal and the pins on the right, they are numbered as such:

Now make the following connections:

  • LCD pin 1 to 5V
  • LCD pin 2 to GND
  • LCD pin 3 to Arduino D4
  • LCD pin 4 to Arduino D5
  • LCD pin 5 to Arduino D6
  • LCD pin 6 to Arduino D7
  • LCD pin 7 – not connected
  • LCD pin 8 – Arduino D8
  • LCD pin 9 to the centre pin of a 10k trimpot – whose other legs connect to 5V and GND. This is used to adjust the contrast of the LCD.

The Arduino digital pins that are used can be changed – they are defined in the header file (see further on). If you were curious as to how low-current these modules are:

That’s 0.689 mA- not bad at all. Great for battery-powered operations. Now that you’ve got the module wired up, let’s get going with some demonstration sketches.

Software setup

The sketches used in this tutorial are based on work by Jeff Albertson and Robert Mech, so kudos to them – however we’ve simplified them a little to make use easier. We’ll just cover the functions required to display data on the LCD. However feel free to review the sketches and files along with the controller chip datasheet as you’ll get an idea of how the controller is driven by the Arduino.

When using the LCD module you’ll need a header file in the same folder as your sketch. You can download the header file from here. Then every time you open a sketch that uses the header file, it should appear in a tab next to the main sketch, for example:

headerinuse

There’s also a group of functions and lines required in your sketch. We’ll run through those now – so download the first example sketch, add the header file and upload it. Your results should be the same as the video below:

So how did that work? Take a look at the sketch you uploaded.  You need all the functions between the two lines of “////////////////////////” and also the five lines in void setup(). Then you can display a string of text or numbers using

which was used in void loop(). You can use the digits 0~9, the alphabet (well, what you can do with 7-segments), the degrees symbol (use an asterix – “*”) and a dash (use  - “-”). So if your sketch can put together the data to display in a string, then that’s taken care of.

If you want to clear the screen, use:

Next – to individually place digits on the screen, use the function:

Where n is the number to be displayed (zero or a positive integer), p is the position on the LCD for the number’s  (the positions from left to right are 11 to 0…), d is the number of digits to the right of the decimal point (leave as zero if you don’t want a decimal point), and l is the number of digits being displayed for n. When you display digits using this function you can use more than one function to compose the number to be displayed – as this function doesn’t clear the screen.

To help get your head around it, the following example sketch (download) has a variety of examples in void loop(). You can watch this example in the following video:

Conclusion

So there you have it – an incredibly inexpensive and possibly useful LCD module. Thank you to Jeff Albertson and Robert Mech for their help and original code.

LEDborder

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.

Posted in arduino, display, education, ktm-s101, ktms101, LCD, lesson, part review, pd7225, tutorialComments (10)

Tutorial: Arduino and the MSGEQ7 Spectrum Analyzer

This is a tutorial on using the MSGEQ7 Spectrum Analyser with Arduino, and chapter forty-eight 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 30/01/2013

In this article we’re going to explain how to make simple spectrum analysers with an Arduino-style board. (Analyser? Analyzer? Take your pick).

First of all, what is a spectrum analyser? Good question. Do you remember what  this is?

It’s a mixed graphic equaliser/spectrum analyser deck for a hi-fi system. The display in the middle is the spectrum analyser, and roughly-speaking it shows the strength of  different frequencies in the music being listened to – and looked pretty awesome doing it. We can recreate displays similar to this for entertainment and also as a base for creative lighting effects. By working through this tutorial you’ll have the base knowledge to recreate these yourself.

We’ll be using the MSGEQ7 “seven band graphic equaliser IC” from Mixed Signal Integration. Here’s the MSGEQ7 data sheet (.pdf).  This little IC can accept a single audio source, analyse seven frequency bands of the audio, and output a DC representation of each frequency band. This isn’t super-accurate or calibrated in any way, but it works. You can get the IC separately, for example:


and then build your own circuit around it… or like most things in the Arduino world – get a shield. In this case, a derivative of the original Bliptronics shield by Sparkfun. It’s designed to pass through stereo audio via 3.5mm audio sockets and contains two MSGEQ7s, so we can do a stereo analyser:

As usual Sparkfun have saved a few cents by not including the stackable header sockets, so you’ll need to buy and solder those in yourself. There is also space for three header pins for direct audio input (left, right and common), which are useful – so if you can add those as well.

So now you have a shield that’s ready for use. Before moving forward let’s examine how the MSGEQ7 works for us. As mentioned earlier, it analyses seven frequency bands. These are illustrated in the following graph from the data sheet:

freqresponse

It will return the strengths of the audio at seven points – 63 Hz, 160 Hz, 400 Hz, 1 kHz, 2.5 kHz, 6.25 kHz and 16 kHz – and as you can see there is some overlap between the bands. The strength is returned as a DC voltage – which we can then simply measure with the Arduino’s analogue input and create a display of some sort. At this point audio purists, Sheldonites and RF people might get a little cranky, so once again – this is more for visual indication than any sort of calibration device.

However as an 8-pin IC a different approach is required to get the different levels. The IC will sequentially give out the levels for each band on pin 3- e.g. 63 Hz then 160 Hz then 400 Hz then 1 kHz then 2.5 kHz then 6.25 kHz  then 16 kHz then back to 63 Hz and so on. To start this sequence we first reset the IC by pulsing the RESET pin HIGH then low. This tells the IC to start at the first band. Next, we set the STROBE pin to LOW, take the DC reading from pin 3 with analogue input, store the value in a variable (an array), then set the STROBE pin HIGH. We repeat the strobe-measure sequence six more times to get the rest of the data, then RESET the IC and start all over again. For the visual learners consider the diagram below from the data sheet:

strobing1

To demonstrate this process, consider the function

in the following example sketch:

If you follow through the sketch, you can see that it reads both left- and right-channel values from the two MSGEQ7s on the shield, then stores each value in the arrays left[] and right[]. These values are then sent to the serial monitor for display – for example:

If you have a function generator, connect the output to one of the channels and GND – then adjust the frequency and amplitude to see how the values change. The following video clip is a short demonstration of this – we set the generator to 1 kHz and adjust the amplitude of the signal. To make things easier to read we only measure and display the left channel:


Keep an eye on the fourth column of data – this is the analogRead() value returned by the Arduino when reading the 1khz frequency band. You can also see the affect on the other bands around 1 kHz as we increase and decrease the frequency. However that wasn’t really visually appealing – so now we’ll create a small and large graphical version.

First we’ll use an inexpensive LCD, the I2C model from akafugu reviewed previously. To save repeating myself, also review how to create custom LCD characters from here.

With the LCD with have two rows of sixteen characters. The plan is to use the top row for the levels, the left-channel’s on … the left, and the right on the right. Each character will be a little bar graph for the level. The bottom row can be for a label. We don’t have too many pixels to work with, but it’s a compact example:

lcdfullon

We have eight rows for each character, and the results from an analogueRead() fall between 0 and 1023. So that’s 1024 possible values spread over eight sections. Thus each row of pixels in each character will represent 128 “units of analogue read” or around 0.63 V if the Arduino is running from true 5 V (remember your AREF notes?). The sketch will again read the values from the MSGEQ7, feed them into two arrays – then display the required character in each band space  on the LCD.

Here’s the resulting sketch:

If you’ve been reading through my tutorials there isn’t anything new to worry about. And now for the demo, with sound -

That would look great on the side of a Walkman, however it’s a bit small. Let’s scale it up by using a Freetronics Dot Matrix Display - you may recall these from Clock One. For some background knowledge check the review here.  Don’t forget to use a suitable power supply for the DMD – 5 V at 4 A will do nicely. The DMD contains 16 rows of 32 LEDs. This gives us twice the “resolution” to display each band level if desired. The display style is subjective, so for this example we’ll use a single column of LEDs for each frequency band, with a blank column between each one.

We use a lot of line-drawing statements to display the levels, and clear the DMD after each display. With this and the previous sketches, there could be room for efficiency – however I write these with the beginner in mind. Here’s the sketch:

… and here it is in action:

Conclusion

At this point you have the knowledge to use the MSGEQ7 ICs to create some interesting spectrum analysers for entertainment and visual appeal – now you just choose the type of display enjoy the results.

LEDborder

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.

Posted in analyser, analyzer, arduino, BLIPTRONICS, com-10468, dev-10306, education, graphic, lesson, MSGEQ7, sparkfun, spectrum, tutorialComments (32)

Kit Review – SC/Jaycar USB Power Monitor

Introduction

Every month Australian electronics magazine Silicon Chip publishes a variety of projects, and in December 2012 they published the USB Power Monitor by Nicholas Vinen. Jaycar picked it up and now offers a kit, the subject of our review. This small device plugs inline between a USB port and another device, and can display the current drawn, power and voltage at the USB port with a large LCD module. This is useful when you’re experimenting with USB-powered devices such as Arduino projects or curious how external USB devices can affect your notebook computer’s battery drain.

Assembly

The kit arrives in typical Jaycar fashion:

… everything necessary is included with the kit:

The instructions arrive as an updated reprint of the original magazine article, plus the usual notes from Jaycar about warranty and their component ID sheet which is useful for beginners. The PCB is quite small, and designed to be around the same size as the LCD module:

As you can see below, most of the work is already done due to the almost exclusive use of SMD components:

That’s a good thing if you’re in a hurry (or not the best with surface-mount work). Therefore the small amount of work requires is simply to solder in the USB sockets, the button and the LCD:

It took less than ten minutes to solder together. However – take careful, careful note of the LCD. There isn’t a pin 1 indicator on the module – so instead hold the LCD up to the light and determine which side of the screen has the decimal points – and line it up matching the silk-screening on the PCB. Once finished you can add the clear heatshrink to protect the meter, but remember to cut a small window at the back if you want access to the ICSP pins for the PIC microcontroller:

How it works

The USB current is passed through a 50 mΩ shunt resistor, with the voltage drop being measured by an INA282 current shunt monitor IC. The signal from there is amplified by an op amp and then fed to the ADC of a PIC18F45K80 microcontroller, which does the calculations and drives the LCD. For complete details purchase the kit or a copy of the December 2012 edition of Silicon Chip.

Operation

First you need to calibrate the unit – when first used the meter defaults to calibration mode. You simply insert it into a USB port. then measure the USB DC voltage brought out to two pads on the meter. By pressing the button you can match the measured voltage against the display as shown below – then you’re done.

Then you simply plug it in between your USB device and the socket. Press the button to change the measurement. The meter can measure the following ranges:

For an operational example. consider the next three images are from charging my phone – with the power, current and voltage being shown:

“P” for power…

current in mA

“b” for bus voltage

If you want to use the USB ports on the right-hand side of your computer, just press the button while inserting the meter – and it flips around:

Finally – here’s a quick video of the meter at work, whilst copying a file to an external USB hard drive:

Conclusion

I really like this – it’s simple and it works. Kudos to Nicholas for his project. You can purchase it from Jaycar and their resellers, or read more about it in the December 2012 edition of Silicon Chip. Full-sized images available on flickr. This kit was purchased without notifying the supplier.

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.

Posted in jaycar, kc5516, kit review, monitor, power, silicon chip, USB

Kit Review – akafugu TWILCD Display Controller Backpacks

Introduction

Working with LCD displays is always useful, for debugging hardware by showing various data or part of a final design. Furthermore, using them can be rather wasteful of I/O pins, especially when trying to squeeze in other functionality. Plus there’s the external contrast adjustment, general wiring and the time taken to get it working. (Don’t believe me? See here).

However, using the subjects of this kit review – you can convert standard HD44780 LCD modules to use the I2C bus using a small backpack-style board – bringing total I/O down to four wires – 5V/3.3V, GND, SDA and SCL. If you’re using an Arduino – don’t panic if you’re not up on I2C – a software library takes care of the translation leaving you to use the LiquidCrystal functions as normal. Furthermore you can control the brightness and contrast (and colour for RGB modules) – this feature alone is just magic and will make building these features into projects much, much easier.

In this review we examine both of the backpacks available from akafugu. There are two available:

  • the TWILCD: Supports 1×16 and 2×7 connectors. It covers 16×1, 20×1, 16×2, 20×2 and 20×4 displays with and without backlight, and the
  • TWILCD 40×2/40×4/RGB: Supports 1×18 connector (for Newhaven RGB backlit displays), 2×8 connector (used for some 20×4 displays) and 2×9 connector (used for 40×4 displays)
If unsure about your LCD, see the list and explanation here. The LCDs used in this article were supplied with the mono and colour LCD bundles available from akafugu. So let’s see how easy they really are, and put them through their paces.

Assembly

The backpacks arrive in the usual anti-static bags:

First we’ll examine the TWILCD board:

Very small indeed. There are three distinct areas of interface – including the single horizontal or dual vertical connectors for various LCDs, and I2C bus lines as well as ICSP connectors for the onboard ATTINY4313 microcontroller. The firmware can be updated and is available on the akafugu github repository. If you look at the horizontal row along the top – there are eighteen holes. This allows for displays that have pins ordered 1~16 and also those with 15,16,1~16 order (15 and 16 are for the LCD backlight).

The next step is to solder in the connectors for power and I2C if so desired, and then the LCD to the backpack. Double-check that you have the pin numbering and alignment correct before soldering, for example:

and then you’re finished:

Simple. Now apply power and after a moment the the backpack firmware will display the I2C bus address:

Success! Now let’s repeat this with the TWILCD 40×2/40×4/RGB version. The backpack itself is still quite small:

… and has various pin alignments for different types of LCD module. Note the extra pins allowing use of RGB-backlit modules and 40×4 character modules. Again,  make sure you have the pins lined up against your LCD module before soldering the backpack in:

 Notice how the I2C connector is between the LCD and the backpack – there is enough space for it to sit in there, and also acts as a perfect spacer when soldering the backpack to the display module.  Once finished soldering, apply 5/3.3V and GND to check your display:

Using the TWILCDs

Using the backpacks is very easy. If you aren’t using an Arduino, libraries for AVR-GCC are available. If you are using the Arduino system, it is very simple. Just download and install the library from here. Don’t forget to connect the SDA and SCL connectors to your Arduino. If you’re unsure about LCD and Arduino – see here.

Programming for the TWILCD is dead simple – just use your existing Arduino sketch, but replace

with

and that’s it. Even creating custom characters. No new functions to learn or tricks to take note of – they just work. Total win. The only new functions you will need are to control the brightness and contrast… to set the brightness, use:

You can also set the brightness level to EEPROM as a default using:

Contrast is equally simple, using:


and

You can see these in action using the example sketches with the Arduino library, and in the following video:

Now for the TWILCD 40×2/40×4/RGB version. You have one more function to set the colour of the text:

where red, green and blue are values between 0 and 254. Easily done. You can see this in action using the test_RGB example sketch included with the library, and shown in the following video:

Conclusion

The TWILCD backpacks are simple, easy to setup and easy to use. They make using LCD displays a lot easier and faster for rapid prototyping, experimenting or making final products easier to use and program. A well-deserved addition to every experimenter’s toolkit. For more information, visit the akafugu product website. Full-size images available on flickr.

Note – the products used in this article were a promotional consideration from akafugu.jp, however the opinions stated are purely my own.

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.

Translated version in Serbo-Croatian language.

Posted in akafugu, arduino, clocks, I2C, kit review, LCD, part review, rgbComments (0)

Kit Review – Snootlab DeuLigne LCD Arduino Shield

Hello everyone

Another month and time for another kit review :) Once again we have another kit from the team at Snootlab in France – their DeuLigne LCD Arduino shield. Apart from having a two row, sixteen character backlit LCD there is also a five-way joystick (up, down, left, right and enter) which is useful for data entry and so on.

This LCD shield is different to any others I have seen on the market as it uses the I2C bus for interface with the LCD screen – thereby not using any digital pins at all. The interfacing is taken care of by a Microchip MCP23008 8-bit port expander IC, and Snootlab have written a custom LCD library which makes using the LCD very simple. Furthermore the joystick uses the analog input method, using analogue pin zero. But for now, let’s examine construction.

Please note that the kit assembled in this article is a version 1.0, however the shield is now at version 1.1. Construction is very easy, starting with the visual and easy to follow instructions (download). The authors really have made an effort to write simple, easy to follow instructions. The kit arrives as expected, in a reusable anti-static pouch:

As always everything was included, including stacking headers for Arduino. It’s great to see them included, as some other companies that should know better sometimes don’t. (Do you hear me Sparkfun?)

The PCB is solid and fabricated very nicely – the silk screen is very descriptive, and the PCB is 1.7mm thick. The joystick is surface-mounted and already fitted. Here’s the top:

… and the bottom:

Using a Freetronics EtherTen as a reference,  you can see that the DeuLigne PCB is somewhat larger than the standard Arduino shield:

The first components to solder in are the resistors:

… followed by the transistor and MCP23008. Do not use an IC socket, as this will block the LCD from seating properly…

After fitting the capacitor, contrast trimpot, LCD header pins and stacking sockets the next step is to bolt in the LCD with the standoffs:

The plastic bolts can be trimmed easily, and then glued to the nuts to stay tight. Or you can just melt them together with the barrel of your soldering iron :) Finally you can solder in the LCD data pins and the shield is finished:

The only thing that concerned me was the limited space between LCD pins twelve~sixteen and the stacking header sockets. It may be preferable to solder the stacking sockets last to avoid possibly melting them when soldering the LCD. Otherwise everything was simple and construction took just under twenty minutes.

Now to get the shield working. Download and install the DeuLigne Arduino library, and then you can test your shield with the included examples. The LCD contrast can be adjusted with the trimpot between the joystick and the reset button. Note that this shield is fully Open Hardware compliant, and all the design files and so on are available from the ‘download’ tab of the shield product page.

Initialising the LCD requires the following code before void Setup():

Then in void Setup():

Now you can make use of the various LCD functions, including:

Reading the joystick position is easy, the function

returns an integer to pos representing the position. Right = 0, left = 3, up = 1, down = 2, enter = 4. Automatic text scrolling can be turned on and off with:

Creating custom characters isn’t that difficult. Each character consists of eight rows of five pixels. Create your character inside a byte array, such as:

There is an excellent tool to create these bytes here. Then allocate the custom character to a position number (0~7) using:

Then to display the custom character, just use:

And the resulting character filling the display:

Now for an example sketch to put it all together. Using my modified Freetronics board with a DS1307 real-time clock IC, we have a simple clock that can be set by using the shield’s joystick. For a refresher on the clock please read this tutorial. And for the sketch:

As you can see, the last delay statement is for 400 milliseconds. Due to the extra overhead required by using I2C on top of the LCD library, it slows down the refresh rate a little. Moving forward, a demonstration video:


So there you have it. Another useful, fun and interesting Arduino shield kit to build and enjoy. Although it is no secret I like Snootlab products, it is a just sentiment. The quality of the kit is first rate, and the instructions and support exists from the designers. So if you need an LCD shield, consider this one.

For support, visit the Snootlab website and customer forum in French (use Google Translate). However as noted previously the team at Snootlab converse in excellent English and have been easy to contact via email if you have any questions. Snootlab products including the Snootlab DeuLigne are available directly from their website. High-resolution images available on flickr.

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

[Disclaimer - the products reviewed in this article are promotional considerations made available by Snootlab]

Posted in arduino, DeuLigne, I2C, kit review, LCD, snootlab, tutorialComments (2)

August 2011 Competition Results

Competition over.

Posted in competitionComments (0)

August 2011 Competition

Competition over!

Posted in competition

Kit review – High Accuracy LC Meter

Hello readers

Time for another kit review. Lately one of my goals has been to make life easier and in doing so having some decent test equipment. One challenge of meeting that goal is (naturally) keeping the cost of things down to a reasonable level. Unfortunately my eyesight is not the best so I cannot read small capacitor markings – which makes a capacitance meter necessary. Although I have that function within my multimeter, it is often required to read resistors in the same work session.

Thus the reason for this kit review. A day trip to Altronics saw me return with (amongst other things) their High Precision LC Meter kit. The details were originally published in the May 2008 issue of Australia’s Silicon Chip magazine. The meter specifications are:

  • Capacitance – 0.1pF to over 800 nF with four-digit resolution;
  • Inductance – 10 nH to over 70 mH with four-digit resolution;
  • Accuracy of better than +/- 1% of the reading;
  • Automatic range selection, however only non-polarised capacitors can be measured.

The power drain is quite low,  between 8 (measurement) and 17 milliamps (calibration). Using a fresh 9V alkaline battery you should realise around fifty to sixty hours of continuous use. At this point some of you may be wondering if it is cheaper to purchase an LC meter or make your own. A quick search found the BK Precision 875B LCR meter with the same C range and a worse L range for over twice the price of the kit. Although we don’t have resistance measurement in our kit, if you are building this you already have a multimeter. So not bad value at all. And you can say you built it :)

Speaking of building, assembly time was just under two hours, and the kit itself is very well produced. The packaging was the typical retail bag:

retailkitss

The first thing that grabs your attention is the housing. It is a genuine, made in the US Hammond enclosure – and has all the required holes and LCD area punched out, so you don’t need to do any drilling at all:

hammondcasess

The enclosure has nice non-slip rubberised edging (the grey area) and also allows for a 9V battery to be housed securely. The team at Altronics have done a great job in redesigning the kit for this enclosure, much more attractive than the magazine version. The PCB is solder-masked and silk-screened to fine standard:

pcbss2

There are two small boards to cut and file off from the main PCB. We will examine them later in the article. All required parts for completion were included, and it is good to see 1% resistors and an IC socket for the microcontroller:

partsss1

At first I was a little disappointed to not have a backlit LCD module, however considering the meter is to be battery operated (however there is a DC socket for a plugpack) and you wouldn’t really be using this in the dark, a backlight wouldn’t be necessary. Construction was easy enough, the layout on the PCB is well labelled, and plenty of space between pins. Lately I have started using a lead-former, and can highly recommend the use of one:

leadformerss

Assembly was quite simple, just start with the lower profile components:

assemble1ss

 

… then mount the LCD and the larger components:

assemble2ss

… the switches and others – and we’re done:

finishedsolderingss

The only problem at this point was the PCB holes for the selector switch, one hole was around 1mm from where it needed to be. Instead of drilling out the hole, it was easier to just bend up the legs of the switch and keep going:

switchlegsss

At this stage one has to cut out two supports from the enclosure, which can be done easily. Then insert the PCB and solder to the sockets and power (9V battery snap). Initial testing was successful (after adjusting the LCD contrast…

inittestss

If you look at the area of PCB between the battery and the left-hand screw there are eight pins – these are four pairs of inputs used to help calibrate and check operation of the meter. For example, by placing a jumper over a pair you can display the oscillator frequency at various stages:

calibrationss

Furthermore, those links can also be used to fine-tune the meter. For example one can increase or decrease the scaling factor and the settings are then stored in the EEPROM within the microcontroller. However my example seemed ok from the start, so it was time to seal up the enclosure and get testing. Starting with a ceramic capacitor, the lowest value in stock:

3p9pfss

Spot-on. That was a good start, however trying to bend the leads to match the binding posts was somewhat inconvenient, so I cut up some leads and fitted crocodile clips on the end. The meter’s zero button allows you to reset the measurement back to zero after attaching the leads, so stray capacitance can be taken into account.

Next, time to check the measurement with something more accurate, a 1% tolerance silvered-mica 100 picofarad capacitor:

99pfss

Again, the meter came through right on specification. My apologies to those looking for inductor tests – I don’t have any in stock to try out. If you are really curious I could be persuaded to order some in, however as the capacitance measurement has been successful I am confident the inductance measurement would also fall within the meter’s specifications.

As shown earlier, there were two smaller PCBs included:

pcbadaptorsss

The top PCB is a shorting bar used to help zero the inductance reading, and the lower PCB is used to help measure smaller capacitors and also SMD units. A nice finishing touch that adds value to the meter. The only optional extra to consider would be a set of short leads with clips or probes to make measurement physically easier.

When reading this kit review it may appear to be somewhat positive and not critical at all. However it really is a  good instrument, considering the accuracy, price, and enjoyment from doing it yourself. It was interesting, easy to build, and will be very useful now and in the future. So if you are in the market for an LC meter, and don’t mind some work – you should add this kit to your checklist for consideration. It is available from Altronics stores and resellers.

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.

Posted in altronics, K2533, kit review, LC meter, learning electronics, test equipmentComments (18)

Tutorial: Arduino and Infra-red control

Learn how to use Arduino and infra-red remote controls in chapter thirty-two of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.

Updated 10/07/2013

In this article we will look at something different to the usual, and hopefully very interesting and useful – interfacing our Arduino systems with infra-red receivers. Why would we want to do this? To have another method to control our Ardiuno-based systems, using simple infra-red remote controls.

A goal of this article is to make things as easy as possible, so we will not look into the base detail of how things work - instead we will examine how to get things done. If you would like a full explanation of infra-red, perhaps see the page on Wikipedia. The remote controls you use for televisions and so on transmit infra-red beam which is turned on and off at a very high speed – usually 38 kHz, to create bits of serial data which are then interpreted by the receiving unit. As the wavelength of infra-red light is too high for human eyes, we cannot see it. However using a digital camera – we can. Here is a demonstration video of IR codes being sent via a particularly fun kit – the adafruit TV-B-Gone:

Now to get started. You will need a remote control, and a matching IR receiver device. The hardware and library used in this tutorial only  supports NEC, Sony SIRC, Philips RC5, Philips RC6, and raw IR protocols. Or you can purchase a matching set for a good price, such as this example:

irpackage

Or you may already have a spare remote laying around somewhere. I kept this example from my old Sony Trinitron CRT TV after it passed away:

sonyremote1

It will more than suffice for a test remote. Now for a receiver – if you have purchased the remote/receiver set, you have a nice unit that is ready to be wired into your Arduino, and also a great remote that is compact and easy to carry about. To connect your receiver module – as per the PCB labels, connect Vcc to Arduino 5V, GND to Arduino GND, and D (the data line) to Arduino digital pin 11.

Our examples use pin 11, however you can alter that later on. If you are using your own remote control, you will just need a receiver module. These are very cheap, and an ideal unit is the Vishay TSOP4138 (data sheet .pdf). These are available from element-14 and the other usual retail suspects. They are also dead-simple to use. Looking at the following example:

From left to right the pins are data, GND and Vcc (to Arduino +5V). So it can be easily wired into a small breadboard for testing purposes. Once you have your remote and receiver module connected, you need to take care of the software side of things. There is a new library to download and install, download it from here. Please note that library doesn’t work for Arduino Leonardo, Freetronics Leostick, etc with ATmega32U4. Instead, use this library (and skip the modification steps below). Extract the IRremote folder and place into the ..\arduinoxxx\libraries folder. Then restart your Arduino IDE if it was already open.

Using Arduino IDE v1.0 or greater? Open the file “IRRemoteInt.h” in the library folder, and change the line

Then save and close the file, restart the Arduino IDE and you’re set.

With our first example, we will receive the commands from our remote control and display them on the serial monitor:

Open the serial monitor box, point your remote control to the receiver and start pressing away. You should see something like this:

What have we here? Lots of hexadecimal numbers. Did you notice that each button on your remote control resulted in an individual hexadecimal number? I hope so. The number FFFFFFFF means that the button was held down. The remote used was from a yum-cha discount TV. Now I will try again with the Sony remote:

This time, each button press resulted in the same code three times. This is peculiar to Sony IR systems. However nothing to worry about. Looking back at the sketch for example 32.1, the

section is critical – if a code has been received, the code within the if statement is executed. The hexadecimal code is stored in the variable

with which we can treat as any normal hexadecimal number. At this point, press a few buttons on your remote control, and take a note of the matching hexadecimal codes that relate to each button. We will need these codes for the next example…

Now we know how to convert the infra-red magic into numbers, we can create sketches to have our Arduino act on particular commands. As the IR library returns hexadecimal numbers, we can use simple decision functions to take action. In the following example, we use switch…case to examine each inbound code, then execute a function. In this case we have an LCD module connected via I2C, and the sketch is programmed to understand fifteen Sony IR codes. If you don’t have an LCD you could always send the output to the serial monitor. If you are using the DFRobot I2C LCD display, you need to use Arduino v23.

Furthermore you can substitute your own values if not using Sony remote controls. Finally, this sketch has a short loop after the translateIR(); function call which ignores the following two codes – we do this as Sony remotes send the same code three times. Again. you can remove this if necessary. Note that when using hexadecimal numbers in our sketch we preced them with 0x:

And here it is in action:


You might be thinking “why would I want to make things appear on the LCD like that?”. The purpose of the example is to show how to react to various IR commands. You can replace the LCD display functions with other functions of your choosing.

At the start working with infra-red may have seemed to be complex, but with the previous two examples it should be quite simple by now. So there you have it, another useful way to control our Arduino systems. Hopefully you have some ideas on how to make use of this technology. In future articles we will examine creating and sending IR codes from our Arduino. Furthermore, a big thanks to Ken Shirriff for his Arduino library.

LEDborder

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.

Posted in arduino, control, DFR0107, dfrobot, education, infrared, IR, learning electronics, lesson, microcontrollers, remote, tronixstuff, tutorialComments (16)

Arduino Game: Tic-Tac-Toe

[Updated 19/02/2013]

Let’s recreate the game of Tic-tac-toe with our Arduino systems. This game is also known as Noughts and Crosses or Three-in-a-row. Whatever we call it, I’m sure you will be familiar with the game from your childhood or general messing about. For the uninitiated, there is an excellent explanation of the game over at Wikipedia.

tttboard

In the following examples, a human will play against the machine (Arduino). The demonstration sketches are almost identical except for one function – machineMove();. This function contains the method of deciding a move for the machine. By localising the machine’s decision making into that function we can experiment with levels of intelligence without worrying about the rest of the sketch. In writing this article it is assumed the reader has some basic Arduino or programming experience. If not, perhaps read some of my Arduino tutorials indexed here.

However first we will examine the hardware. I have used my well-worn Freetronics Eleven board, which is equivalent to the Arduino Uno. For a display, the Sparkfun LCD shield is used. For user input we have two buttons connected to digital pins 6 and 7, using 10k pull-down resistors as normal. The buttons are wired via a ScrewShield set. To save time I have used my generic button-board, whose schematic is below:

example12p3schematic

 

If you were to construct a more permanent example, this could be easily done. One could possibly use a DS touch-screen over their LCD. Perhaps for mark II? Nevertheless, time to move on. Now to explain how the sketch works – please download a copy from here so you can follow along with the explanation.

I have tried to make the sketch as modular as possible to make it easy to follow and modify. The sketch itself is relatively simple. We use an array board[] to map the pieces of the game board in memory – board[0] being the top-left and board[8] being the bottom-right position. We create a graphical representation of the board by drawing rectangles for the horizontal and vertical lines, lines to form crosses, and circles for … circles. The function drawBoard(); takes care of the board lines and calls drawPiece(); to place the players’ pieces. drawBoard(); reads the board[] array to determine if a position is blank (zero), a nought (1) or a cross (2).

The flow of the sketch is easy to follow. First the function introScreen() is called – it displays the introductory screen. Then drawBoard() is called to draw the initially-blank game board. Then the main function playGame(); is called. We have a global variable winner, whose value determine the winner of the game (0 – game still in play, 1 – human, 2 – machine, 3 – draw). playGame(); and other functions will refer to winner throughout the sketch. Within playGame();, the human and machine take turns placing their pieces. The function humanMove(); accepts the human’s choice in piece position, storing it into board[], and not allowing false moves. The function machineMove(); controls the decision-making process for the machine’s moves. In the first example, the machine moves by randomly selecting a board position. If the position is taken, another random position is selected (and so on) until a valid move can be made.

After each instance of humanMove(); and machineMove();, the function checkWinner(); is called. This function compares the contents of the array board[] against all possible scenarios for a win by either player, and calls the function drawTest(); – which checks for a draw – and stores the result in the variable winner as described earlier. Checking for a win is simple, however checking for a draw was a little more complex. This involves counting the number of 1s and 2s in the board[] array. If there are five 1s and four 2s or four 1s and five 2s ( in other words, the board is full) there is a draw. Easy!

If, after the function checkWinner(); is called, the varible winner >0 – then something to end the game has happened – either a win or a draw. This is determined using the switch…case function at the end of checkWinner();. At this point a function relative to the game status is called, each of which display the outcome and wait for the user to press button A to start a new game. At the end of each of these functions, we call the function clearBoard(); – which resets the array board[] and winner back to zero, ready for the next battle of wits.

Now for our first example in action. The function machineMove() is an example of the simplest form of play – the machine randomly selects blank positions on the board until the game ends. In the following video clip you can see this in action:

For the forthcoming examples, we will allow the choice of who moves first. This is accomplished with the function moveFirst(); which sets the variable whofirst to 1 for human first, or 2 for machine first. This is read by playGame() to determine the first move. Now let’s inject some strategy into our machineMove(); function to give the machine a slight edge above sheer randomness.

In the following example, the machine will first only use the centre or corners until those positions have been taken. This is accomplished by placing the position numbers into another array strategy1[]={0,2,4,6,8} which the machine will randomly select from until those positions are used.  Once all those positions have been filled, the machine will revert to random positioning to attempt a win. You can download this example sketch from here. Do you think the machine can win if allowed to move first? Let’s see what happens in the following video clip:

In the second example the player who moves first will generally have the advantage. From this point, how could we strengthen the machine’s level of intelligence to improve its strategy? If you have a better method, and can integrate it into the example sketch, and are happy to publish it under Creative Commons – email the sketch to john at tronixstuff dot com.

So there you have it, some variations on a classic game translated for our Arduino systems. I hope you found it interesting… or at least something different to read about.

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.

Posted in arduino, education, games, LCD-09363, lesson, microcontrollers, tutorialComments (4)

The DFRobot LCD4884 LCD Shield

Learn how to use the DFRobot LCD4884 Arduino LCD shield.

Updated 19/03/2013

This needs to be updated for use with Arduino IDE v1.0.1 and greater… however we no longer have a shield to test it. Stay tuned via twitter to find out when this is updated.

This article is my response to a request on how to use the LCD4884 LCD shield from DFRobot in China. It is a simple way of displaying text and the odd graphic, as well as another way to accept user input. Here is the shield in question:

image

From a hardware perspective the LCD has a resolution of 84 by 48 pixels, with a blue back light. It can easily display six rows of fourteen alphanumeric characters, or two rows of six very large characters. Furthermore, it can display bitmap images that are appropriately sized. At the top-left of the shield digital pins eight to thirteen have been expanded with matching Vcc and GND pins, and at the bottom right the same has been done with analogue pins one through to five. Therefore if using this shield, you will lose digital pins two through to seven and analogue zero.

Along the bottom-left of the shield are solder pads for some other I/O options, however I couldn’t find any documentation on how these are used. Below the LCD is a small four-way joystick that also has an integral button. This is connected to analog pin zero via a resistor network. This joystick can be used for user input and also to create some nifty menu systems. To the right is a power-on LED which is really too bright, I would recommend sanding it a little to reduce the intensity, or just melting it off with a soldering iron.

The shield requires an Arduino library which can be downloaded from the shield’s wiki page. There is also a good demonstration sketch on the wiki, however some of our readers may find this to be somewhat complex. Therefore where possible I will break down and explain the functions in order to simplify use of the shield, then use them in a demonstration sketch.

Controlling the backlight is very easy, just use:

digitalWrite(7, HIGH/LOW)

to turn it on and off. Don’t forget to put

pinMode(7, OUTPUT) in void setup();.

Reading the joystick position is accomplished via analogRead(0);. It returns the following values as such:

  • Up – 505
  • Down – 0
  • Left – 740
  • Right – 330
  • pressed in – 144
  • Idle (no action) – 1023

By using analogRead(0) and if… statements you can read the joystick in a simple way. Don’t forget to allow for some tolerance in the readings. Attempts to press the button while forcing a direction did not return any different values. In the example sketch later on, you can see how this is implemented. Always remember to insert:

in void setup() to create an instance of the LCD, and

at the start of your sketch to enable the library.

Now to display text on the LCD. Here is an example of the standard font text:

charactersss

Using the standard font, we can position text using the following function:

The parameter x is for the x-coordinate of the first character – measured in pixels, not characters. However y is the coordinate in character lines (!). The screen can display six lines of fourteen characters. To display the larger font, for example:

largechar

use the following:

Unfortunately the library only supports the digits 0~9, +, – and decimal point. You can modify the file font_big.h in the library folder and create your own characters. Once again the x parameter is the number of pixels across to place the first character, and y is 0 for the top line and 3 for the bottom line. Notice that the characters in this font are proportional, however the maximum number of digits to plan for in one line would be six.

To clear the display, use:

By now you will be able to display text, control the backlight and read the joystick. The following demonstration sketch puts it all together so far:

Next is to create and display bitmap images. Images can be up to 84 x 48 pixels in size. There are no shades of grey in the images, just pixels on or off. To display a bitmap is a convoluted process but can be mastered. We need to convert a bitmap image into hexadecimal numbers which are then stored in a text file for inclusion into the sketch. To do so, follow these steps:

Create your monochrome image using an editor such as Gimp. Make sure your file name ends with .bmp. Such as:

gimpexample

Next, download the BMP2ASM program from this website. [Sorry, could only find a Windows version]. Open your .bmp file as created above, and you will see a whole bunch of hexadecimal numbers at the bottom of the window:

convexam

Turn on the check boxes labelled “Stretch”, “Use Prefix” and “Use suffix”. Then click “Convert”. Have a look in your folder and you will find a text file with an extension .asm. Open this file in a text editor such as Notepad. Remove all the instances of “dt”, as well as the top line with the file path and name. Finally, put commas at the end of each line.

You should now be left with a file of hexadecimal numbers. Encase these numbers in the form of an array as such:

encase

What we have done is places the hexadecimal numbers inside the

declaration. To make life simpler, ensure the filename (ending with .h) is the same as the variable name, as in this example it is called hellobmp(.h). And make sure you have saved this file in the same folder as the sketch that will use it. Finally, we include the hellobmp.h file in our example sketch to display the image:

Notice in the function lcd.LCD_draw_bmp_pixel the filename hellobmp is the same as in the #include declaration is the same as the hellobmp.h file we created. They all need to match. Furthermore, the four numerical parameters are the bitmap’s top-left x-y and bottom-right x-y coordinates on the LCD. So after all that, here is the result:

hellodone

So there you have it. If you have any questions about this LCD shield contact DF Studio, or ask a question in our Google Group.

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.

Posted in arduino, DFR0092, dfrobot, education, LCD, LCD4884, lesson, review, tutorialComments (23)

Tutorial: Arduino and TFT LCD

Old and now unsupported tutorial for 4D Systems 1.44″ TFT serial interface LCD.

Update 20/04/2013 

The Arduino library for this module hasn’t been updated to work with Arduino v1.0.1+ – so you need to use Arduino IDE v22 or v23. And the module itself has been discontinued. For the time being I’m leaving the tutorial here until a more suitable item can be used. We can’t help you with the 4D module

Nevertheless – if you have one – here’s the subject of the tutorial- the 4D Systems 1.44″ TFT serial interface LCD:

The LCD is an LED-backlit thin-film transistor type, resolution is 128 x 128 pixels, with an RGB colour range of 65536.

As an aside, this is a very powerful piece of hardware. The module not only contains a 1.44″ square TFT LCD, there is also a dedicated graphics processor and a microSD card interface. One can program the display processor in the same manner as another microcontroller platform for incredibly interesting results. For more information, please visit:

http://www.4dsystems.com.au/prod.php?id=120

However in the spirit of keeping things simple, this article will focus on driving the LCD directly using our Arduino or compatible boards. There are two firmware versions of this module – the GFX and the SGC. We need to have the SGC firmware, as this allows control via the serial TX/RX pins from our Arduno board. If you have purchased the SGC module, you’re ready to go. Scroll down until you see “And we’re back…”. However if you have the GFX version, please read the following instructions on how to change your LCD’s firmware from GFX to SGC…

Changing the firmware from GFX to SGC

  • At the moment this process only seems available to users of Microsoft Windows. All complaints to 4D Systems.
  • Unfortunately this process may not work with an Arduino Mega board.
  • First of all, remove the ATmega328 from your Arduino board. Please be careful, use a chip puller if possible. We are going to use the board as a simple serial-USB converter;
  • Insert your LCD module into a solderless breadboard;
  • Connect Arduino pin 0 (RX) to display pin 7 (RX); connect Arduino pin 1 (TX) to display pin 8 (TX). [Yes - TX>TX, RX>RX];
  • Connect Arduino 5V to display pin 9; connect Arduino GND to display pin 6; your LCD should display the following:

beforesgc

  • Visit http://www.4dsystems.com.au/prod.php?id=46, download and open the PmmC Loader application; visit http://www.4dsystems.com.au/prod.php?id=120 and download the .pmmc file to your local drive;
  • Connect your Arduino board via USB to the computer; then run the PmmC loader application;
  • Select the appropriate COM: port, load in the .pmmc file, then click Load. The firmware update should take less than sixty seconds;
  • When finished, you will be presented with the following on the computer:

progfinish

… and the following on your LCD:

aftersgcss

  • At this point unplug the USB lead from your Arduino board and all leads into the Arduino board;
  • Re-insert the ATmega328 back into your Arduino board;
  • Reconnect the wires from the LCD module to the Arduino, but this time connect Arduino TX to LCD RX; and LCD TX to Arduino RX.
  • Now you have  the serial-interface SGC firmware model LCD.

And we’re back…

To control this LCD, it requires commands to be sent via Serial.write(), and such commands are in the form of hexadecimal numbers. (You see something new every day). You can download the reference book with all the commands:

http://tronixstuff.com/wp-content/uploads/2011/02/goldelox-sgc-commands-sis-rev3.pdf

and bypass the library by directly writing the hexadecimal numbers directly to the module.

However, to get up to speed as fast as possible we can use a library with more of the popular functions included. Kudos and thanks to Oscar Gonzalez for writing a very useful library. Download the library from:

http://code.google.com/p/displayshield4d/downloads/list

and install into your ../Arduino-002x/libraries folder, then re-start the Arduino IDE if you had it running. You may be wondering why the library is named displayshield4d - the LCD manufacturer sells this LCD on an Arduino shield. Although that would be great for experimenting, one would need to purchase another standalone LCD if their project moved forward – myself included. So that’s why we’re using the bare LCD board.

To connect the LCD to our Arduino is very simple:

  • LCD pin 5 to Arduino RST;
  • LCD pin 6 to Arduino GND;
  • LCD pin 7 to Arduino D1;
  • LCD pin 8 to Arduino D0;
  • LCD pin 9 to Arduino 5V.

In the following examples we will demonstrate the various functions available in the library. As this is chapter 29, I will no longer explain the more basic functions or ideas that you should know by now, instead relying on comments within the sketch if it feels necessary. It can take a short moment for the LCD controller to process, so always put a short delay between functions.

When uploading a sketch to your Arduino you may need to disconnect the LCD from Arduino D0/D1 as it can interfere with the serial process.

Firstly we will demonstrate text display. Initialising the display requires a few functions:

The second line creates an instance of lcd to be used with the relevant functions. Next, within void setup():

To write text to the LCD, the following function is required:

This line sets the font transparency. If we use the parameter OLED_FONT_TRANSPARENT the unused pixels in the character area will be transparent and continue to show what they were set to before the text was over-written with. You can also use OLED_FONT_OPAQUE, which blocks the item displayed “behind” the text.

Whenever a function requires a colour parameter, we use:

where x, y and z are numerical values (between 0 and 255) for the red, green and blue components of the required colour. If you need an RGB numerical reference, download this handy chart. Finally, to display some text we use the following:

The parameters required are:

  • a – the x-position of the first character. E.g. if this was a zero, the top-left pixel of the first character would be on the left-most pixel column of the LCD;
  • b – the y-position of the first character. e.g. if both a and b were zero, the text would start from the top-left of the LCD;
  • c – numerical code for the font to use: 1 is for 5×7 pixel characters, 2 for 8×8 and 3 for 8×12;
  • the three values within the lcd.RGB() function determine the colour of the text;
  • d – x-axis resolution multiplier. E.g. if you double this and use the 5×7 font, the characters will be double-width;
  • e – y-axis resolution multiplier.

Now let’s see this in action with the following sketch:

And a short video clip of the example in action: - http://www.youtube.com/watch?v=t3yypXL022w

As you can see the display update speed is much better than the LCD from the previous chapter. Although this example was short, don’t be afraid to try out your own parameters in the example sketch.

Next we will demonstrate the various graphics functions in the library. Creating graphics isn’t rocket science, it just takes some imagination (something I admit to lacking) and following the parameters for each function. Our first is

which places a pixel on the screen at location x,y of colour described using lcd.RGB(). Next we have

which draws a line from x1, y1 to x2, y2 of colour rgb. One can also create rectangles and so on using

This will create a rectangle with the top-left point at x,y; width is l pixels, height is h pixels, and a new parameter z. If z is 0, the function will draw a solid shape, if z is 1, it will display only a wire-frame rectangle with a pixel width of one. Circles are created using

where x and y are the coordinates for the centre of the circle, r is the radius, and z is the solid/wireframe parameter. And finally – triangles:

This will draw a triangle with the corners at the coordinate parameters; z again is the solid/wireframe parameter. However you need to order the corners in an anti-clockwise order. This will become evident in the example sketch below. In this example we run through the graphical functions described above. By following through the sketch you should gain an idea of how the graphical functions are used, in order to create your own displays.

And here is the video of example 29.2 in action … brought to you by Mr Blurrycam: - http://www.youtube.com/watch?v=BKy-GuKWGZ8

 

Posted in 4d systems, arduino, education, LCD, learning electronics, lesson, microcontrollers, TFT, tutorial

The world’s smallest oscilloscope??

Hello readers

Today we examine a tiny and fascinating piece of test equipment from Gabotronics – their XMEGA Xprotolab. Sure, that sounds like a lot – and it is. Yet the functionality of the Xprotolab is inversely proportional to its physical size. Try to imagine having an oscilloscope, arbitrary waveform generator, logic analyser and a spectrum analyser – including a display – in a package no larger than 25.4 x 40.6 mm (1″ x 1.6″) in size. Well imagine no more as here it is:

1ss

As described above, this tiny marvel of engineering has the following functions:

  • Two analogue oscilloscope channels with a maximum sampling rate of 2 million samples per second;
  • Analogue bandwidth of 320 kHz at 8-bits resolution;
  • Buffer size of 256 samples;
  • Fast fourier-transform;
  • Analog and external digital triggering;
  • Maximum input voltage of +/- 10V;
  • Automatic average and peak-to-peak measurements;
  • Logic analyser with eight channel maximum simultaneous monitoring;
  • Firmware is user upgradable;
  • Can also be used as a development board for the XMEGA microcontroller (extra items required);
  • When powered from a USB cable, the board can supply +/-5V and +3.3V into a solderless breadboard.

The OLED screen is very clear and precise, which considering the size of 0.96″ – very easy to read. One can also set the display mode to invert which changes the display to black on white, bringing back memories of the original Apple Macintosh:

invertedss

Using the Xprotolab took a little getting used to, however after pressing menu buttons for a few minutes I had it worked out. The more sensible among you will no doubt read the instructions and menu map listed at the website. Having the dual voltmeter function is quite useful, it saved me having to mess about with a couple of multimeters when trying to debug some analogue circuits I’m currently working with.

The display can be as complex or as simple as you choose, for example when working with the oscilloscope you can disable one channel and shift the waveform so it occupies the centre of the screen. Or when working with the logic analyser, you can choose to only select the channels being monitored, instead of filling the screen with unused logic lines.

There are a couple of things to take care with. When inserting the Xprotolab into your breadboard, be careful not to put pressure on the OLED display when pushing down; when removing it from the breadboard, try and do so evenly with the help of an DIP IC puller.

Generally in my reviews there is a video clip of something happening. Unfortunately my camera just isn’t that good, so below is the demonstration clip from the manufacturer:

As you can see the Xprotolab would be quite useful for monitoring various signals whilst prototyping, as you can just drop it into a breadboard. Furthermore, if your required range is measurable the Xprotolab saves you having to look back-and-forth between a prototype and the display from a regular oscilloscope as well.

As the purchase price is relatively cheap compared against the time and effort of trying to make an OLED display board yourself, one could also plan to build an Xprotolab into a final design – considering a lot of measurement and display work is already done for you it could be a real time-saver. The Xprotolab can run from a 5V supply and only draws a maximum of 60 milliamps. Product support is quite extensive, including source code, schematics, videos, a user forum and more available from the product page.

In conclusion the Xprotolab is genuinely useful, inexpensive and ready to use out of the box. It would make a useful piece of test equipment for a beginner or seasoned professional, and also integrates well into custom projects when required.

Remember, if you have any questions about the Xprotolab,  please contact Gabotronics via their website.

[Note - the Xprotolab reviewed in this article was received from Gabotronics for review purposes]

Posted in gabotronics, oscilloscope, part review, review, xmega, xprotolabComments (9)

Tutorial: Arduino and Colour LCD

Learn how to use the colour LCD shield from Sparkfun in chapter twenty-eight 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 19/02/2013

Although there are many colour LCDs on the market, I’ve chosen a relatively simple and popular model to examine in this tutorial – the Sparkfun Color LCD shield:

If you buy one note (shown above) that stacking headers aren’t supplied or fitted to the shield. If you get a header pack from Sparkfun or elsewhere – order PRT-10007 not PRT-11417 as the LCD shield doesn’t have the extra holes for R3 Arduino boards. However if you do have an Arduino R3 – relax … the shield works. 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 unit is 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.x\libraries folder. Then restart the Arduino IDE if it was already open.

At this point let’s check the shield is working before moving forward. Fit it to your Arduino – making sure the shield doesn’t make contact with the USB socket**. Then open the Arduino IDE and upload the TestPattern sketch found in the Examples folder. You should be presented with a nice test pattern as such:

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.

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

as well as the following in void setup():