Posts with «tutorial» label

Tutorial – Arduino and MC14489 LED Display Driver

Learn how to use MC14489 LED display driver ICs with Arduino in chapter fifty-one 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 12/05/2013

Introduction

Recently we’ve been looking at alternatives to the MAX7219 LED display driver IC due to pricing and availability issues (stay tuned for that one) – and came across an old but still quite useful IC – the MC14489 from Motorola (now Freescale Semiconductor). The MC14489 can drive five seven-segment LED numbers with decimal point, or a combination of numbers and separate LEDs. You can also daisy-chain more than one to drive more digits, and it’s controlled with a simple serial data-clock method in the same way as a 74HC595 shift register. Sourcing the MC14489 isn’t too difficult – it’s available from element14, Newark, Digikey, and so on – or if you’re not in a hurry, try the usual suspects like Futurlec.

For the purpose of the tutorial we’ll show you how to send commands easily from your Arduino or compatible board to control a five-digit 7-segment LED display module – and the instructions are quite simple so they should translate easily to other platforms. Once you have mastered the single module, using more than one MC14489 will be just as easy. So let’s get started.

Hardware

Before moving forward, download the data sheet (pdf). You will need to refer to this as you build the circuit(s). And here’s our subject in real life:

For our demonstration display we’ll be using a vintage HP 5082-7415 LED display module. However you can use almost any 7-segment modules as long as they’re common-cathode – for example, Sparkfun part number COM-11405. If you’re using a four-digit module and want an extra digit, you can add another single digit display. If you want a ruler, the design files are here.

Connecting the MC14489 to an LED display isn’t complex at all. From the data sheet consider Figure 9:

Each of the anode control pins from the MC14489 connect to the matching anodes on your display module, and the BANK1~5 pins connect to the matching digit cathode pins on the display module. You can find the MC14489 pin assignments on page 1 of the data sheet. Seeing as this is chapter fifty-one  – by now you should be confident with finding such information on the data sheets, so I will be encouraging you to do a little more of the work.

Interesting point – you don’t need current-limiting resistors. However you do need the resistor Rx – this controls the current flow to each LED segment. But which value to use? You need to find out the forward current of your LED display (for example 20 mA) then check Figure 7 on page 7 of the data sheet:

To be conservative I’m using a value of 2k0 for Rx, however you can choose your own based on the data sheet for your display and the graph above.  Next – connect the data, clock and enable pins of the MC14489 to three Arduino digital pints – for our example we’re using 5, 6 and 7 for data, clock and enable respectively. Then it’s just 5V and GND to Arduino 5V and GND – and put a 0.1uF capacitor between 5V and GND. Before moving on double-check the connections – especially between the MC14489 and the LED display.

Controlling the MC14489

To control the display we need to send data to two registers in the MC14489 – the configuration register  (one byte) and the display register (three bytes). See page 9 of the data sheet for the overview. The MC14489 will understand that if we send out one byte of data it is to send it the configuration register, and if it receives three bytes of data to send it to the display register. To keep things simple we’ll only worry about the first bit (C0) in the configuration register – this turns the display outputs on or off. To do this, use the following:

digitalWrite(enable, LOW);
shiftOut(data, clock, MSBFIRST, B00000001); // used binary for clarity, however you can use decimal or hexadecimal numbers
digitalWrite(enable, HIGH);
delay(10);

and to turn it off, send bit C0 as zero. The small delay is necessary after each command.

Once you have turned the display on – the next step is to send three bytes of data which represent the numbers to display and decimal points if necessary. Review the table on page 8 of the data sheet. See how they have the binary nibble values for the digits in the third column. Thankfully the nibble for each digit is the binary value for that digit. Furthermore you might want to set the decimal point – that is set using three bits in the first nibble of the three bytes (go back to page 9 and see the display register). Finally you can halve the brightness by setting the very first bit to zero (or one for full brightness).

As an example for that – if you want to display 5.4321 the three bytes of data to send in binary will be:

1101 0101 0100 0011 0010 0001

Let’s break that down. The first bit is 1 for full brightness, then the next three bits (101) turn on the decimal point for BANK5 (the left-most digit). Then you have five nibbles of data, one for each of the digits from left to right. So there’s binary for 5, then four, then three, then two, then one.

digitalWrite(enable, LOW); 
shiftOut(data, clock, MSBFIRST, B11010101); // D23~D16 
shiftOut(data, clock, MSBFIRST, B01000011); // D15~D8
shiftOut(data, clock, MSBFIRST, B00100001); // D7~D0
digitalWrite(enable, HIGH);
delay(10);

To demonstrate everything described so far, it’s been neatly packaged into our first example sketch:

// Example 51.1
// Motorola MC14489 with HP 5082-7415 5-digit, 7-segment LED display
// 2k0 resistor on MC14489 Rx pin
// John Boxall 2013 CC by-sa-nc
// define pins for data from Arduino to MC14489
// we treat it just like a 74HC595
int data = 5;
int clock = 6;
int enable = 7;
void setup()
{
 pinMode(data, OUTPUT);
 pinMode(enable, OUTPUT);
 pinMode(clock, OUTPUT);
 displayOn(); // display defaults to off at power-up
}
void displayTest1()
// displays 5.4321
{
 digitalWrite(enable, LOW); // send 3 bytes to display register. See data sheet page 9
 // you can also insert decimal or hexadecimal numbers in place of the binary numbers
 // we're using binary as you can easily match the nibbles (4-bits) against the table
 // in data sheet page 8
 shiftOut(data, clock, MSBFIRST, B11010101); // D23~D16
 shiftOut(data, clock, MSBFIRST, B01000011); // D15~D8
 shiftOut(data, clock, MSBFIRST, B00100001); // D7~D0
 digitalWrite(enable, HIGH);
 delay(10);
}
void displayTest2()
// displays ABCDE
{
 digitalWrite(enable, LOW); // send 3 bytes to display register. See data sheet page 9
 // you can also insert decimal or hexadecimal numbers in place of the binary numbers
 // we're using binary as you can easily match the nibbles (4-bits) against the table
 // in data sheet page 8
 shiftOut(data, clock, MSBFIRST, B10001010); // D23~D16
 shiftOut(data, clock, MSBFIRST, B10111100); // D15~D8
 shiftOut(data, clock, MSBFIRST, B11011110); // D7~D0
 digitalWrite(enable, HIGH);
 delay(10);
}
void displayOn()
// turns on display
{
 digitalWrite(enable, LOW);
 shiftOut(data, clock, MSBFIRST, B00000001);
 digitalWrite(enable, HIGH);
 delay(10);
}
void displayOff()
// turns off display
{
 digitalWrite(enable, LOW);
 shiftOut(data, clock, MSBFIRST, B00000000);
 digitalWrite(enable, HIGH);
 delay(10);
}
void loop()
{
 displayOn();
 displayTest1();
 delay(1000);
 displayTest2();
 delay(1000);
 displayOff();
 delay(500);
}

… with the results in the following video:


Now that we can display numbers and a few letters with binary, life would be easier if there was a way to take a number and just send it to the display.

So consider the following function that takes an integer between 0 and 99999, does the work and sends it to the display:

void displayIntLong(long x)
// takes a long between 0~99999 and sends it to the MC14489
{
 int numbers[5];
 byte a=0; 
 byte b=0; 
 byte c=0; // will hold the three bytes to send to the MC14489 

 // first split the incoming long into five separate digits
 numbers[0] = int ( x / 10000 ); // left-most digit (will be BANK5)
 x = x % 10000; 
 numbers[1] = int ( x / 1000 );
 x = x % 1000; 
 numbers[2] = int ( x / 100 );
 x = x % 100; 
 numbers[3] = int ( x / 10 );
 x = x % 10; 
 numbers[4] = x % 10; // right-most digit (will be BANK1)

 // now to create the three bytes to send to the MC14489
 // build byte c which holds digits 4 and 5
 c = numbers[3];
 c = c << 4; // move the nibble to the left
 c = c | numbers[4];
 // build byte b which holds digits 3 and 4
 b = numbers [1];
 b = b << 4;
 b = b | numbers[2];
 // build byte a which holds the brightness bit, decimal points and digit 1
 a = B10000000 | numbers[0]; // full brightness, no decimal points

 // now send the bytes to the MC14489
 digitalWrite(enable, LOW);
 shiftOut(data, clock, MSBFIRST, a);
 shiftOut(data, clock, MSBFIRST, b);
 shiftOut(data, clock, MSBFIRST, c); 
 digitalWrite(enable, HIGH);
 delay(10); 
}

So how does that work? First it splits the 5-digit number into separate digits and stores them in the array numbers[]. It then places the fourth digit into a byte, then moves the data four bits to the left – then we bitwise OR the fifth digit into the same byte. This leaves us with a byte of data containing the nibbles for the fourth and fifth digit. The process is repeated for digits 2 and 3. Finally the brightness bit and decimal point bits are assigned to another byte which then has the first digit’s nibble OR’d into it. Which leaves us with bytes a, b and c ready to send to the MC14489. Note that there isn’t any error-checking – however you could add a test to check that the number to be displayed was within the parameter, and if not either switch off the display (see example 51.1) or throw up all the decimal points or … whatever you want.

You can download the demonstration sketch for the function – Example 51.2, and view the results in the following video:

You can also display the letters A to F by sending the values 10 to 15 respectivel to each digit’s nibble. However that would be part of a larger application, which you can (hopefully) by now work out for yourself. Furthermore there’s some other characters that can be displayed – however trying to display the alphabet using 7-segment displays is somewhat passé. Instead, get some 16-segment LED modules or an LCD.

Finally, you can cascade more than one MC14489 to control more digits. Just run a connection from the data out pin on the first MC14889 to the data pin of the second one, and all the clock and enable lines together. Then send out more data – see page 11 of the data sheet. If you’re going to do that in volume other ICs may be a cheaper option and thus lead you back to the MAX7219.

Conclusion

For a chance find the MC14489 is a fun an inexpensive way to drive those LED digit displays. We haven’t covered every single possible option or feature of the part – however you will now have the core knowledge to go further with the MC14489 if you need to move further with it. And if you enjoy my tutorials, or want to introduce someone else to the interesting world of Arduino – check out my new book “Arduino Workshop” from No Starch Press.

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.

The post Tutorial – Arduino and MC14489 LED Display Driver appeared first on tronixstuff.

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

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

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

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

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

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

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

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Book – “Arduino Workshop – A Hands-On Introduction with 65 Projects” appeared first on tronixstuff.

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

#include "UTFT.h"
UTFT myGLCD(ILI9325C,19,18,17,16); // for Arduino Uno

and in void setup():

myGLCD.InitLCD(orientation); 
myGLCD.clrScr();

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

extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];

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

myGLCD.setColor(red, green, blue); 
myGLCD.setBackColor(red, green, blue);

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:

myGLCD.setFont(SmallFont); // Allows 20 rows of 40 characters
myGLCD.setFont(BigFont); // Allows 15 rows of 20 characters
myGLCD.setFont(SevenSegNumFont); // allows display of 0 to 9 over four rows

Now to display the text use the function:

myGLCD.print("text to display",x, y);

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:

myGLCD.print("Hello, world", 20, 20, angle);

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:

Displaying Graphics

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

myGLCD.fillScr(red, green, blue);

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

myGLCD.drawPixel(x,y);

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

myGLCD.drawLine(x1,0,x2,239);

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

myGLCD.drawRect(x1,y2,x2,y2); // for open rectangles
myGLCD.fillRect(x1,y2,x2,y2); // for filled rectangles

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:

myGLCD.drawRoundRect(x1,y2,x2,y2); // for open rectangles
myGLCD.fillRoundRect(x1,y2,x2,y2); // for filled rectangles

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

myGLCD.drawCircle(x,y,r); // draws open circle
myGLCD.fillCircle(x,y,r); // draws a filled circle

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:

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:

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:

myGLCD.drawBitmap(x,y,width,height, name, scale);

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:

myGLCD.drawBitmap(x,y,width,height, name, angle, cx, cy);

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.

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.

The post Tutorial – Arduino and ILI9325 colour TFT LCD modules appeared first on tronixstuff.

Tronixstuff 26 Apr 02:31

Bluetooth Android Processing 2

PART TWO


If you happened to land on this page and missed PART ONE, I would advise you go back and read that section first. You may get lost coming in half way through the story. This is what you'll find in part one.
  • Downloading and setting up the Android SDK
  • Downloading the Processing IDE
  • Setting up and preparing the Android device
  • Running through a couple of Processing/Android sketches on an Andoid phone.
In the last sketch we checked to see if Bluetooth was enabled, if not, we then asked for permission to turn it on. The screen would then display a different colour depending on the Bluetooth state. So let's keep on going,


ToastMaster - the master of all Toasts

I will now introduce you to Toast. What does "Toast" have to do with programming ? Toast is used by Android to quietly display little messages on the screen.
Have a look here for a a quick introduction to Toast, otherwise have a look at the Android Developers Toast information.

I will be creating my own method that relies on Toast to make the process of displaying messages easier. I have named this method: "ToastMaster".
A word of warning. Calling ToastMaster from within setup() will cause errorsin the DiscoverBluetooth sketch (further down this page).
This will not happen in every sketch, but the Discoverbluetooth sketch has subActivities which may cause some sort of conflict.. I did warn you.

Here is a quick look at my ToastMaster method (no need to compile this code):
1
2
3
4
5
6
7
8
/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_LONG);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}

Here is a breakdown of what this is doing:
  • Toast.makeText() - is used to construct the message to be displayed. 
  • getApplicationContext() - gets a handle on the Application
  • textToDisplay - is obvious, this is the text you want to display.
  • Toast.LENGTH_LONG - is how long you want the message to displayed for. (or LENGTH_SHORT)
  • setGravity() - sets the message position on the screen, in this case I have chosen to center the text.
  • show() - is used to actually show the message.

Broadcast Receivers : Looking out for Bluetooth devices
To listen/look out for any Bluetooth devices that are within range, we need to create and  register a Broadcast receiver.
When registering a BroadcastReceiver, you will need to tell the program what it is you are looking / listening out for. In our case we want to listen out for occasions whereby a Bluetooth device is FOUND.  This is represented by:
If a BluetoothDevice is found, then the designated BroadcastReceiver will be called. We make our own BroadcastReceiver in order to perform a task such as displaying the name of the discovered device on the phone. However, before you will find anything, you have to start Discovering. This is done by calling the startDiscovery() method of the default Bluetooth adapter.

Here are the relevant components:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver myDiscoverer =
new myOwnBroadcastReceiver();
//Within Setup()
if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
if (!bluetooth.isDiscovering()){
bluetooth.startDiscovery();
}
}

/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);

//Display the name of the discovered device
ToastMaster("
Discovered: " + discoveredDeviceName);
}
}




Discovering Bluetooth devices: putting it all together

You will notice that in the following sketch, we have to import a whole lot more. Which is why I have tried to break it down into bite size chunks, to help you digest it all. Now we will put it all together into a sketch which will
  • ask to turn Bluetooth ON if it happens to be disabled.
  • If you don't turn on Bluetooth, it will tell you that you need to turn it on.
  • If you turn on bluetooth (or if it was already on), it will try to discover any bluetooth devices in range. These devices need to be made "discoverable" before running this sketch.
  • If the phone finds a bluetooth device, it will display the name of the device and will change the background screen colour to GREEN.
Android/Processing Sketch 4: DiscoverBluetooth
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* DiscoverBluetooth: Written by ScottC on 18 March 2013 using 
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform */


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

boolean foundDevice=
false; //When this is true, the screen turns green.
//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==0){
if(resultCode == RESULT_OK){
ToastMaster("
Bluetooth has been switched ON");
}
else {
ToastMaster("
You need to turn Bluetooth ON !!!");
}
}
}


/* Create a Broadcast Receiver that will later be used to
receive the names of Bluetooth devices in range. */

BroadcastReceiver myDiscoverer =
new myOwnBroadcastReceiver();


void setup(){
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth =
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}

/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */

if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()){
bluetooth.startDiscovery();
}
}
}


void draw(){
//Display a green screen if a device has been found
if(foundDevice){
background(10,255,10);
}
}


/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);

//Display the name of the discovered device
ToastMaster("
Discovered: " + discoveredDeviceName);

//Change foundDevice to true which will make the screen turn green
foundDevice=
true;
}
}


/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_LONG);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}


Upgrading the Broadcast Receiver : More Device info

Ok, we have the device name. But what other information can we collect from the device? You can call
This will return the discovered BluetoothDevice, which can then be probed to find the following information.
  • .getName()   =  Which is a different way of getting the name of the BluetoothDevice.
  • .getAddress() = Returns the hardware address of the BluetoothDevice.  eg. "00:11:22:AA:BB:CC"
  • .getBondState() = Returns an integer which describes the BondState of the BluetoothDevice
These are the three possible BondStates 
Here is an updated version of the custom BroadcastReceiver class (myOwnBroadcastReceiver) from the DiscoverBluetooth sketch described above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("
Discovered: " + discoveredDeviceName);

//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("
getAddress() = " + discoveredDevice.getAddress());
ToastMaster("
getName() = " + discoveredDevice.getName());

int bondyState=discoveredDevice.getBondState();
ToastMaster("
getBondState() = " + bondyState);

String mybondState;
switch(bondyState){
case 10: mybondState="BOND_NONE";
break;
case 11: mybondState="BOND_BONDING";
break;
case 12: mybondState="BOND_BONDED";
break;
default: mybondState="INVALID BOND STATE";
break;
}
ToastMaster("
getBondState() = " + mybondState);

//Change foundDevice to true which will make the screen turn green
foundDevice=
true;
}
}

If you replace the old version of  myOwnBroadcastReceiver with this one, you will know a little bit more about the devices discovered.


Connecting to the Bluetooth Device:
While we now have more information about the Bluetooth device, we don't really need it, and we will get rid of it by the end of the tutorial, however we will keep it here for the time being. In the next updated sketch we will be making a connection to the discovered device, and turning the background purple when the connection is made. In order to do this we will need to
  • Create a boolean variable to hold the connection status
  • Create and register a new BroadcastReceiver to notify us when a connection broadcast action has been received.
  • Create a new thread to handle the connection
  • Change the background screen colour when a successful connection has been made
First we need the boolean to hold the connection status:
  • boolean BTisConnected=false;
When the boolean is true, the screen will change to purple. The draw() method will be updated to accommodate this requirement.
Next we will create and register a new BroadcastReceiver, it is created using this:
  • BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
This broadcastreceiver will be used to notify us when a connection has been made. Therefore we need to register the (BluetoothDevice.ACTION_ACL_CONNECTED)
action with the BroadcastReceiver in the following way
  • registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
We will need to update myOwnBroadcastReceiver() to be able to differentiate beween this action and the (BluetoothDevice.ACTION_FOUND) action used already. This is done by first getting the action from the intent variable described in the onReceive() method within myOwnBroadcastReceiver().
  • String action=intent.getAction();
We can differentiate the two actions using the following simplified code in myOwnBroadcastReceiver:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();

//Notification that BluetoothDevice is FOUND
if(BluetoothDevice.ACTION_FOUND.equals(action)){
foundDevice=
true; //Change the screen to green
}

//Notification if bluetooth device is connected
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
BTisConnected=
true; //turn screen purple
}
}
}

Now that we can be notified about the connection made to the Bluetooth Device, lets go through the code required to make the connection. We will only connect if we have actually discovered a device, so we will put this code within the FOUND section of myOwnBroadcastReceiver.

1
2
3
4
5
6
7
8
 //Connect to the discovered bluetooth device (SeeedBTSlave)
if(discoveredDeviceName.equals("SeeedBTSlave")){
unregisterReceiver(myDiscoverer);
ConnectToBluetooth connectBT =
new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}

We use the discoveredDeviceName variable to specifically target the Bluetooth device we wish to connect to. We then unregister the myDiscoverer BroadcastReceiver because we are going to stop discovering before we connect to the Bluetooth Device, plus if you don't, it will generate an error. We then pass our discovered device to a new Thread to connect to that device in the background.  The class used to handle the connection is the "ConnectToBluetooth" class as displayed below:

We will cancelDiscovery() on the bluetooth Adapter to prevent a slow connection.
Also we will need to use a specific UUID as per below:
  • private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
I have tried changing the UUID, but changing it to a different number prevented it from establishing a connection.
Before you can connect to the Bluetooth shield you need to use the UUID to create a BluetoothSocket.
  • mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
Once you have the socket, you can then try to connect using:
  • mySocket.connect();
Make sure you have some way of closing the socket, this is done in the cancel() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class ConnectToBluetooth implements Runnable{
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try{
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException){
//Problem with creating a socket
}
}

@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

try{
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */

mySocket.connect();
}
catch (IOException connectException){
try{
mySocket.close();
//try to close the socket
}
catch(IOException closeException){
}
return;
}
}

/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e){
}
}
}

The major structure of this code was made possible using the following site:
http://jayxie.com/mirrors/android-sdk/guide/topics/wireless/bluetooth.html

And the following sites were also useful in getting some of the information I needed:
http://stackoverflow.com/questions/13238600/use-registerreceiver-for-non-activity-and-non-service-class
http://developer.android.com/guide/topics/connectivity/bluetooth.html


While I have described all the major components required to connect to the Bluetooth Device, I will now put it all together in a new and updated version of the "DiscoverBluetooth" Android/Processing sketch and call it "ConnectBluetooth". There is some additional code in this sketch which I did not specifically go through, for example, the code used to turn the background to purple in the draw() method. Look out for that one. Anyway, read through the following code, and make sure that you understand what each section is doing.

Android/Processing Sketch 5: ConnectBluetooth
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/* ConnectBluetooth: Written by ScottC on 18 March 2013 using 
Processing version 2.0b8
Tested on a Samsung Galaxy SII, with Android version 2.3.4
Android ADK - API 10 SDK platform */


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.util.Log;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

boolean foundDevice=
false; //When true, the screen turns green.
boolean BTisConnected=
false; //When true, the screen turns purple.


//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

/*The startActivityForResult() within setup() launches an
Activity which is used to request the user to turn Bluetooth on.
The following onActivityResult() method is called when this
Activity exits. */

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==0){
if(resultCode == RESULT_OK){
ToastMaster("
Bluetooth has been switched ON");
}
else {
ToastMaster("
You need to turn Bluetooth ON !!!");
}
}
}


/* Create a BroadcastReceiver that will later be used to
receive the names of Bluetooth devices in range. */

BroadcastReceiver myDiscoverer =
new myOwnBroadcastReceiver();
/* Create a BroadcastReceiver that will later be used to
identify if the Bluetooth device is connected */

BroadcastReceiver checkIsConnected =
new myOwnBroadcastReceiver();

void setup(){
orientation(LANDSCAPE);
/*IF Bluetooth is NOT enabled, then ask user permission to enable it */
if (!bluetooth.isEnabled()) {
Intent requestBluetooth =
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(requestBluetooth, 0);
}

/*If Bluetooth is now enabled, then register a broadcastReceiver to report any
discovered Bluetooth devices, and then start discovering */

if (bluetooth.isEnabled()) {
registerReceiver(myDiscoverer,
new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(checkIsConnected,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

//Start bluetooth discovery if it is not doing so already
if (!bluetooth.isDiscovering()){
bluetooth.startDiscovery();
}
}
}


void draw(){
//Display a green screen if a device has been found,
//Display a purple screen when a connection is made to the device
if(foundDevice){
if(BTisConnected){
background(170,50,255);
// purple screen
}
else {
background(10,255,10);
// green screen
}
}
}


/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
ToastMaster("
ACTION:" + action);

//Notification that BluetoothDevice is FOUND
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Display the name of the discovered device
String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
ToastMaster("
Discovered: " + discoveredDeviceName);

//Display more information about the discovered device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("
getAddress() = " + discoveredDevice.getAddress());
ToastMaster("
getName() = " + discoveredDevice.getName());

int bondyState=discoveredDevice.getBondState();
ToastMaster("
getBondState() = " + bondyState);

String mybondState;
switch(bondyState){
case 10: mybondState="BOND_NONE";
break;
case 11: mybondState="BOND_BONDING";
break;
case 12: mybondState="BOND_BONDED";
break;
default: mybondState="INVALID BOND STATE";
break;
}
ToastMaster("
getBondState() = " + mybondState);

//Change foundDevice to true which will make the screen turn green
foundDevice=
true;

//Connect to the discovered bluetooth device (SeeedBTSlave)
if(discoveredDeviceName.equals("SeeedBTSlave")){
ToastMaster("
Connecting you Now !!");
unregisterReceiver(myDiscoverer);
ConnectToBluetooth connectBT =
new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}

//Notification if bluetooth device is connected
if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
ToastMaster("
CONNECTED _ YAY");
BTisConnected=
true; //turn screen purple
}
}
}
public class ConnectToBluetooth implements Runnable{
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try{
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException){
//Problem with creating a socket
}
}

@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();

try{
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */

mySocket.connect();
}
catch (IOException connectException){
try{
mySocket.close();
//try to close the socket
}
catch(IOException closeException){
}
return;
}
}

/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e){
}
}
}

/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
Toast myMessage = Toast.makeText(getApplicationContext(),
textToDisplay,
Toast.LENGTH_SHORT);
myMessage.setGravity(Gravity.CENTER, 0, 0);
myMessage.show();
}


The Arduino Sketch

Most of the Android/Processing code used so far has depended on a Bluetooth Device being discoverable. Our ultimate aim it to connect to a Bluetooth Shield on an Arduino UNO or compatible board such as the Freetronics Eleven. The following sketch was essentially taken from one of my previous posts (here), however, I have stripped it down to the bear essentials so that it will only be discoverable, and will not send or receive data. I will provide this functionality later. I just wanted to show you the essential bits to establish the connection to the Shield.

ARDUINO Sketch 1: Bluetooth Pair and Connect
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* This project combines the code from a few different sources.
This project was put together by ScottC on the 22/03/2013
http://arduinobasics.blogspot.com/

Bluetooth slave code by Steve Chang - downloaded from :
http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield

This sketch does nothing more than setup bluetooth
connection capabilities. It does not send or receive data.

*/


#include <SoftwareSerial.h>
//Software Serial Port

#define RxD 6
// This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7
// This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

#define DEBUG_ENABLED 1

SoftwareSerial blueToothSerial(RxD,TxD);
/*----------------------SETUP----------------------------*/ void setup() {
Serial.begin(9600);
// Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT);
// Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT);
// Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13,OUTPUT);
// Use onboard LED if required.
setupBlueToothConnection();
//Used to initialise the Bluetooth shield
}
/*----------------------LOOP----------------------------*/ void loop() {
digitalWrite(13,LOW);
//Turn off the onboard Arduino LED
}

//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
blueToothSerial.begin(38400);
//Set BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("
\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blueToothSerial.print("
\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("
\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("
\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000);
// This delay is required.
blueToothSerial.print("
\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
Serial.println("
The slave bluetooth is inquirable!");
delay(2000);
// This delay is required.
blueToothSerial.flush();
}



Please make sure to setup the Bluetooth jumpers as per the picture below, otherwise you will not have much luck with the sketch above.






Well that brings us to the end of part TWO.

PART THREE
In part three we will attempt to actually send some data from the Android phone to the Arduino via Bluetooth, and vice versa. This will be when the real fun starts.


or GO BACK
Click on the link if you missed PART ONE

Bluetooth Android Processing 1


PART ONE


Introduction

This is a four part tutorial which will take you through step-by-step on how to create Android apps on your Mobile device that will allow you to communicate with your Arduino over Bluetooth. This tutorial is based upon the Windows environment and an Android device like the Samsung Galaxy S2 Phone.
I will take you through setting up your computer and phone, and will move through in stages so that you understand what each part of the bluetooth code is actually doing. Obviously you will need to ensure that you have a Bluetooth Shield on your Arduino to be able to walk through this tutorial with me.
If you are not interested in the step-by-step instructions, you can jump straight to the end (Part 4) which will have the complete Arduino and Android/Processing code that was used in the following video:

The Goal of this project (Video)


Setting up Processing for Android applications:
For the latest and most up to date version, please follow the instructions on this website: http://wiki.processing.org/w/Android

    Step One:
    Download the Android SDK from this website:
    http://developer.android.com/sdk/index.html

    Android SDK Download:
    Make sure to select the "Use and Existing IDE" link, as per the picture below.



    When you select the "Use an Existing IDE" link, it will then show you the appropriate download to use. This is what it should look like.

    Select the "Download the SDK Tools for Windows" link.
    Once you have downloaded the Android SDK, go ahead and install it as per the instructions below.
    These instruction can also be found here.






    Installing the necessary packages in the Android SDK Manager program
    Make the following 3 selections:
    • Tools: Android SDK Platform-tools
    • API 10: SDK Platform
    • Extras: Google USB Driver
    Then select the button on the bottom-right to install your selections.

    Here is a picture of the Android SDK Manager selections:


    While you may decide to download other packages,
    you MUST download API 10: SDK Platform .
    Do not leave this one out !!



    Step Two: Processing Download

    Download the latest Processing IDE(version 2.0 Beta 8) from this website:
    http://processing.org/download/

    I am using Windows 7, and have chosen to download the Windows 32 bit version as shown below.




    Load Processing, and switch to Android mode, as per the image below.




    You should now have an empty sketch window which looks something like this.





    Step Three: Setting up the Android Hardware device (Phone)
    For the latest steps you can have a look at this site:
    http://developer.android.com/tools/device.html

    However, these are the ones that I carried out:

    Turn on USB debugging on your Android Phone:
    To find out what Android Version you are on, have a look at
        Settings > About Phone : look for heading "Android Version".
    • My Android version is 2.3.4 on my Samsung Galaxy S2.
    To Enable USB Debugging:
       
    Settings > Applications > Development > Select (or Enable) USB debugging

      For those of you who have a different Android version, have a look below:





      Downloading the USB driver for your Android Phone(Windows Users)
      If you are developing on Windows and would like to connect an Android-powered device to test your applications, then you need to install the appropriate USB driver. Have a look at this site for more information on how to download the USB driver for your phone:
      http://developer.android.com/tools/extras/oem-usb.html

      I have a Samsung Galaxy S2 phone, so I had to go to the Samsung Site here:
      http://www.samsung.com/us/support/downloads

      But because I am not in the USA, I had to click on the link for "non-US products":
      http://www.samsung.com/us/support/downloads/global

      You will need the model number of your phone:
      On the Samsung Galaxy S2, you can go into
          Settings > About Phone => Model number. Otherwise, it is located behind the battery.
      • My Phone's Model Number is: GT-I9100
      See the image below for the link to press if you have a non-US phone.



      Then I continued with the install of the USB driver as per the document below:
      http://developer.android.com/tools/extras/oem-usb.html







      Step Four: Android-Processing Sketch
      We will now test our our current setup and make sure that we can run a simple Processing Sketch on the Phone. Bluetooth functionality will be tested later on, so all we need for this step, is our computer, our Android phone, and a USB cable. While it is possible to run this sketch without an Android phone (by using the emulator), I personally do not have the patience to wait an eternity while the emulator boots up... (yes, it takes an eternity)... In this tutorial, we are going to test it on the device (phone).
      This sketch has an orange background and a black circle which you can move around the screen with your finger (that's it) - I did say it was going to be a simple sketch.

      Copy and paste the following Android-Processing sketch into the IDE, and then press the (Run on Device) button, which is the triangle button or press Ctrl-R.


      Android/Processing Sketch 1: Circle Dragger

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      /*Circle Dragger: Simple Android-Processing Sketch written by ScottC on 13/03/2013.
      Visit: http://arduinobasics.blogspot.com/
      */

      int circleWidth = 150;
      void setup(){
      orientation(LANDSCAPE);
      }
      void draw(){
      background(255,100,0);
      fill(0);
      ellipse(mouseX,mouseY,circleWidth,circleWidth);
      }


      You should see an orange screen appear on your phone. Move your finger across the screen and watch as the black circle follows your finger.
      No, not rocket science, but hopefully everything worked as planned. If you want to change the colour of the background or circle, this is a good site:
      http://www.colorpicker.com/



      Step Five: Bluetooth testing:
      We are now going to walk through Bluetooth connectivity. While we could just use a library to do all the heavy lifting for us, I decided to explore Bluetooth functionality from scratch. This will hopefully provide greater returns in the long run. Ok, lets create a new Android/Processing Sketch which changes its behaviour depending on whether Bluetooth is enabled or disabled when the sketch is run. We will display a red screen when Bluetooth is switched off, and green when Bluetooth is switched on.

      To enable Bluetooth on my Samsung Galaxy SII phone:
      • Settings >Wireless and Network > Bluetooth Settings > Bluetooth (Turn on Bluetooth) - check the box

      To disable Bluetooth on my Samsung Galaxy SII phone:
      • Settings >Wireless and Network > Bluetooth Settings > Bluetooth - Uncheck the box

      In the processing/android IDE, you need to make sure that you update the AndroidManifest.xml file to grant specific permissions. You can either edit the file manually in the sketch folder, however, it is much easier and safer to do the following. In the processing/android IDE, select:
      •   Android > Sketch permissions  (as per the picture below)

      • Make sure that BLUETOOTH and BLUETOOTH_ADMIN are selected (as per the picture below). Then press the OK button.


      Then copy and paste the following sketch into the processing/android IDE:


      Android/Processing Sketch 2: BluetoothChecker1
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      /*BluetoothChecker1: Written by ScottC on 17 March 2013
      This will show a red screen if Bluetooth is off,
      and a green screen when Bluetooth is switched on */


      import android.bluetooth.BluetoothAdapter;

      BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
      void setup(){
      orientation(LANDSCAPE);
      }
      void draw(){
      if(bluetooth.isEnabled()){
      background(10,255,30);
      }
      else {
      background(255,10,30);
      }
      }


      When you run the BluetoothChecker1 sketch on the device, you will either see a red screen or a green screen depending on whether you had Bluetooth enabled or disabled at the time. Ok, pretty boring, but it is a start. What if we wanted to ask the USER if they would like to enable Bluetooth at the beginning? We could then change the appearance of the screen depending on their selected answer. Before we add this functionality, I would recommend that you read about the following concepts introduced in the next sketch.
      While it is actually possible to turn bluetooth on without asking for permission, I thought I would retain my manners for the following sketch:

      Android/Processing Sketch 3: BluetoothChecker2
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      /*BluetoothChecker2: Written by ScottC on 17 March 2013

      If Bluetooth is already ON when you run this sketch,
      the background will display BLUE.

      If Bluetooth is OFF when you run this sketch but you
      agree to turn it on, the background will display GREEN.

      If Bluetooth is OFF when you run this sketch and then
      choose to keep it off, the background will display RED.

      =======================================================*/


      import android.bluetooth.BluetoothAdapter;
      import android.content.Intent;
      int BACKGND=0; //Set the background to BLUE
      //Get the default Bluetooth adapter
      BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

      /*The startActivityForResult() launches an Activity which is
      used to request the user to turn Bluetooth on.
      The following onActivityResult() method is called when the
      Activity exits. */

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data){
      if(requestCode==0){
      if(resultCode == RESULT_OK){
      BACKGND=2;
      //Set the background to GREEN
      }
      else {
      BACKGND=1;
      //Set the background to RED
      }
      }
      }
      void setup(){
      orientation(LANDSCAPE);

      /*IF Bluetooth is NOT enabled,
      then ask user permission to enable it */

      if (!bluetooth.isEnabled()) {
      Intent requestBluetooth =
      new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(requestBluetooth, 0);
      }
      }
      void draw(){
      if(BACKGND==0){
      background(10,10,255);
      //Set background to BLUE
      }
      else if(BACKGND==1) {
      background(255,10,10);
      //Set background to RED
      }
      else {
      background(10,255,10);
      //Set background to GREEN
      }
      }

      I tried my best to explain the code via the comments within. I hope it made sense.


      Useful Links:

      Android Processing Wiki: http://wiki.processing.org/w/Android

      Here is a good tutorial which helped me put Processing and Android together:
      http://www.creativeapplications.net/android/mobile-app-development-processing-android-tutorial/

      And most importantly:
      The Android Developers site : Bluetooth



      Click here for PART TWO

      Click here for PART THREE

      Click here for PART FOUR

       
       



      If you like this page, please do me a favour and show your appreciation :

       
      Visit my ArduinoBasics Google + page.
      Follow me on Twitter by looking for ScottC @ArduinoBasics.
      Have a look at my videos on my YouTube channel.


       
       

       
       
       


      However, if you do not have a google profile...
      Feel free to share this page with your friends in any way you see fit.

      Project: Clock Four – Scrolling text clock

      Introduction

      Time for another instalment in my highly-irregular series of irregular clock projects.  In this we have “Clock Four” – a scrolling text clock. After examining some Freetronics Dot Matrix Displays in the stock, it occurred to me that it would be neat to display the time as it was spoken (or close to it) – and thus this the clock was born. It is a quick project – we give you enough to get going with the hardware and sketch, and then you can take it further to suit your needs.

      Hardware

      You’ll need three major items – An Arduino Uno-compatible board, a real-time clock circuit or module using either a DS1307 or DS3232 IC, and a Freetronics DMD. You might want an external power supply, but we’ll get to that later on.

      The first stage is to fit your real-time clock. If you are unfamiliar with the operation of real-time clock circuits, check out the last section of this tutorial. You can build a RTC circuit onto a protoshield or if you have a Freetronics Eleven, it can all fit in the prototyping space as such:

      If you have an RTC module, it will also fit in the same space, then you simply run some wires to the 5V, GND, A4 (for SDA) and A5 (for SCL):

      By now I hope you’re thinking “how do you set the time?”. There’s two answers to that question. If you’re using the DS3232 just set it in the sketch (see below) as the accuracy is very good, you only need to upload the sketch with the new time twice a year to cover daylight savings (unless you live in Queensland). Otherwise add a simple user-interface – a couple of buttons could do it, just as we did with Clock Two. Finally you just need to put the hardware on the back of the DMD. There’s plenty of scope to meet your own needs, a simple solution might be to align the control board so you can access the USB socket with ease – and then stick it down with some Sugru:

      With regards to powering the clock – you can run ONE DMD from the Arduino, and it runs at a good brightness for indoor use. If you want the DMD to run at full, retina-burning brightness you need to use a separate 5 V 4 A power supply. If you’re using two DMDs – that goes to 8 A, and so on. Simply connect the external power to one DMD’s terminals (connect the second or more DMDs to these terminals):

      The Arduino Sketch

      You can download the sketch from here. Please use IDE v1.0.1 . The sketch has the usual functions to set and retrieve the time from DS1307/3232 real-time clock ICs, and as usual with all our clocks you can enter the time information into the variables in void setup(), then uncomment setDateDs1307(), upload the sketch, re-comment setDateDs1307, then upload the sketch once more. Repeat that process to re-set the time if you didn’t add any hardware-based user interface.

      Once the time is retrieved in void loop(), it is passed to the function createTextTime(). This function creates the text string to display by starting with “It’s “, and then determines which words to follow depending on the current time. Finally the function drawText() converts the string holding the text to display into a character variable which can be passed to the DMD.

      And here it is in action:

      Conclusion

      This was a quick project, however I hope you found it either entertaining or useful – and another random type of clock that’s easy to reproduce or modify yourself. We’re already working on another one which is completely different, so stay tuned.

      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.

      The post Project: Clock Four – Scrolling text clock appeared first on tronixstuff.

      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:

      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

      ktmWriteString();

      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:

      ktmCommand(_ClearDsp);

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

      tmPrnNumb(n,p,d,l);

      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.

      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.

      The post Arduino and KTM-S1201 LCD modules appeared first on tronixstuff.

      Basics of ARDUINO BOARD...

      The video explains some basics of ARDUINO BOARD and its related components...

      Exploring the TI Stellaris platform with Energia Arduino-compatible IDE

      Introduction

      In the same manner as their MSP430 development board, Texas Instruments also have another LaunchPad board with their powerful Stellaris LM4F120H5QR microcontroller. It’s an incredibly powerful and well-featured MCU – which offers an 80 MHz, 32-bit ARM Cortex-M4 CPU with floating point, 256 Kbytes of 100,000 write-erase cycle FLASH and many peripherals such as 1MSPS ADCs, eight UARTs, four SPIs, four I2Cs, USB & up to 27 timers, some configurable up to 64-bits.

      That’s a bucket of power, memory and I/O for not much money – you can get the LaunchPad board for around $15. This LaunchPad has the in-circuit debugger, two user buttons, an RGB LED and connectors for I/O and shield-like booster packs:

      and the other side:

      However the good news as far as we’re concerned is that you can now use it with the Energia Arduino-compatible IDE that we examined previously. Before rushing out to order your own Stellaris board, install Energia and examine the available functions and libraries to make sure you can run what you need. And if so, you’re set for some cheap Arduino power.

      Installation

      Installation is simple, just get your download from here. If you’re running Windows 7 – get the USB drivers from here. When you plug your LaunchPad into the USB for the first time, wait until after Windows attempts to install the drivers, then install drivers manually after download via Device manager … three times (JTAG, virtual serial port and DFU device). Use the debug USB socket (and set the switch to debug) when installing and uploading code. If you get the following warning from Windows, just click “Install this driver software anyway”:

      Once the drivers are installed, plug in your LaunchPad, wait a moment – then run Energia. You can then select your board type and serial port just like the Arduino IDE. Then go ahead and upload the “blink” example…

      Awesome – check out all that free memory space. In the same manner as the MSP430, there are some hardware<>sketch differences you need to be aware of. For example, how to refer to the I/O pins in Energia? A map has been provided for front:

      … and back:

      As you can imagine, the Stellaris MCUs are different to an AVR, so a lot of hardware-specific code doesn’t port over from the world of Arduino. One of the first things to remember is that the Stellaris is a 3.3V device. Code may or may not be interchangeable, so a little research will be needed to match up the I/O pins and rewrite the sketch accordingly. For example, instead of digital pins numbers, you use PX_Y – see the map above. So let’s say you want to run through the RGB LED… consider the following sketch:

      int wait = 500;
      void setup() 
      { 
       // initialize the digital pin as an output.
       pinMode(PF_1, OUTPUT); // red 
       pinMode(PF_3, OUTPUT); // green
       pinMode(PF_2, OUTPUT); // blue
      }
      void loop() 
      {
       digitalWrite(PF_1, HIGH); 
       delay(wait); 
       digitalWrite(PF_1, LOW); 
       digitalWrite(PF_3, HIGH); 
       delay(wait); 
       digitalWrite(PF_3, LOW); 
       digitalWrite(PF_2, HIGH); 
       delay(wait); 
       digitalWrite(PF_2, LOW); 
      }

      Which simply blinks the red, green and blue LED elements in series. Using digital inputs is in the same vein, and again the buttons are wired so when pressed they go LOW. An example of this in the following sketch:

      void setup() 
      { 
       // initialize the digital pins
       pinMode(PF_1, OUTPUT); // red 
       pinMode(PF_3, OUTPUT); // green
       pinMode(PF_2, OUTPUT); // blue
      
       pinMode(PF_4, INPUT_PULLUP); // left - note _PULLUP
       pinMode(PF_0, INPUT_PULLUP); // right - note _PULLUP 
      }
      void blinkfast() 
      {
       for (int i=0; i<10; i++)
       {
       digitalWrite(PF_1, HIGH); 
       delay(250); 
       digitalWrite(PF_1, LOW); 
       digitalWrite(PF_3, HIGH); 
       delay(250); 
       digitalWrite(PF_3, LOW); 
       digitalWrite(PF_2, HIGH); 
       delay(250); 
       digitalWrite(PF_2, LOW); 
       }
      }
      void blinkslow() 
      {
       for (int i=0; i<5; i++)
       {
       digitalWrite(PF_1, HIGH); 
       delay(1000); 
       digitalWrite(PF_1, LOW); 
       digitalWrite(PF_3, HIGH); 
       delay(1000); 
       digitalWrite(PF_3, LOW); 
       digitalWrite(PF_2, HIGH); 
       delay(1000); 
       digitalWrite(PF_2, LOW); 
       }
      }
      void loop()
      {
       if (digitalRead(PF_4)==LOW) { blinkslow(); }
       if (digitalRead(PF_0)==LOW) { blinkfast(); }
      }

      And for the non-believers:

      Where to from here? 

      Sometimes you can be platform agnostic, and just pick something that does what you want with the minimum of time and budget. Or to put it another way, if you need a fast CPU and plenty of space but couldn’t be bothered don’t have time to work with Keil, Code Composer Studio, IAR etc – the Energia/Stellaris combination could solve your problem. There’s a growing Energia/Stellaris forum, and libraries can be found here. At the time of writing we found an I2C library as well.

      However to take full advantage of the board, consider going back to the TI tools and move forward with them. You can go further with the tutorials and CCS etc from Texas Instruments own pages.

      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.

      The post Exploring the TI Stellaris platform with Energia Arduino-compatible IDE appeared first on tronixstuff.

      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 10/11/2014

      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:

      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:

      To demonstrate this process, consider the function

      readMSGEQ7()

      in the following example sketch:

      // Example 48.1 - tronixstuff.com/tutorials > chapter 48 - 30 Jan 2013 
      // MSGEQ7 spectrum analyser shield - basic demonstration
      int strobe = 4; // strobe pins on digital 4
      int res = 5; // reset pins on digital 5
      int left[7]; // store band values in these arrays
      int right[7];
      int band;
      void setup()
      {
       Serial.begin(115200);
       pinMode(res, OUTPUT); // reset
       pinMode(strobe, OUTPUT); // strobe
       digitalWrite(res,LOW); // reset low
       digitalWrite(strobe,HIGH); //pin 5 is RESET on the shield
      }
      void readMSGEQ7()
      // Function to read 7 band equalizers
      {
       digitalWrite(res, HIGH);
       digitalWrite(res, LOW);
       for(band=0; band <7; band++)
       {
       digitalWrite(strobe,LOW); // strobe pin on the shield - kicks the IC up to the next band 
       delayMicroseconds(30); // 
       left[band] = analogRead(0); // store left band reading
       right[band] = analogRead(1); // ... and the right
       digitalWrite(strobe,HIGH); 
       }
      }
      void loop()
      {
       readMSGEQ7();
       // display values of left channel on serial monitor
       for (band = 0; band < 7; band++)
       {
       Serial.print(left[band]);
       Serial.print(" ");
       }
       Serial.println();
      // display values of right channel on serial monitor
       for (band = 0; band < 7; band++)
       {
       Serial.print(right[band]);
       Serial.print(" ");
       }
       Serial.println();
      }

      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:

      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:

      // Example 48.2 - tronixstuff.com/tutorials > chapter 48 - 30 Jan 2013 
      // MSGEQ7 spectrum analyser shield and I2C LCD from akafugu
      // for akafugu I2C LCD
      #include "Wire.h"
      #include "TWILiquidCrystal.h"
      LiquidCrystal lcd(50);
      // create custom characters for LCD
      byte level0[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111};
      byte level1[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111};
      byte level2[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111};
      byte level3[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111};
      byte level4[8] = { 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111};
      byte level5[8] = { 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111};
      byte level6[8] = { 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111};
      byte level7[8] = { 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111};
      int strobe = 4; // strobe pins on digital 4
      int res = 5; // reset pins on digital 5
      int left[7]; // store band values in these arrays
      int right[7];
      int band;
      void setup()
      {
       Serial.begin(9600);
       // setup LCD and custom characters
       lcd.begin(16, 2);
       lcd.setContrast(24);
       lcd.clear();
      lcd.createChar(0,level0);
       lcd.createChar(1,level1);
       lcd.createChar(2,level2);
       lcd.createChar(3,level3);
       lcd.createChar(4,level4);
       lcd.createChar(5,level5);
       lcd.createChar(6,level6);
       lcd.createChar(7,level7);
       lcd.setCursor(0,1);
       lcd.print("Left");
       lcd.setCursor(11,1);
       lcd.print("Right");
       pinMode(res, OUTPUT); // reset
       pinMode(strobe, OUTPUT); // strobe
       digitalWrite(res,LOW); // reset low
       digitalWrite(strobe,HIGH); //pin 5 is RESET on the shield
      }
      void readMSGEQ7()
      // Function to read 7 band equalizers
      {
       digitalWrite(res, HIGH);
       digitalWrite(res, LOW);
       for( band = 0; band < 7; band++ )
       {
       digitalWrite(strobe,LOW); // strobe pin on the shield - kicks the IC up to the next band 
       delayMicroseconds(30); // 
       left[band] = analogRead(0); // store left band reading
       right[band] = analogRead(1); // ... and the right
       digitalWrite(strobe,HIGH); 
       }
      }
      void loop()
      {
       readMSGEQ7();
      // display values of left channel on LCD
       for( band = 0; band < 7; band++ )
       {
       lcd.setCursor(band,0);
       if (left[band]>=895) { lcd.write(7); } else
       if (left[band]>=767) { lcd.write(6); } else
       if (left[band]>=639) { lcd.write(5); } else
       if (left[band]>=511) { lcd.write(4); } else
       if (left[band]>=383) { lcd.write(3); } else
       if (left[band]>=255) { lcd.write(2); } else
       if (left[band]>=127) { lcd.write(1); } else
       if (left[band]>=0) { lcd.write(0); }
       }
       // display values of right channel on LCD
       for( band = 0; band < 7; band++ )
       {
       lcd.setCursor(band+9,0);
       if (right[band]>=895) { lcd.write(7); } else
       if (right[band]>=767) { lcd.write(6); } else
       if (right[band]>=639) { lcd.write(5); } else
       if (right[band]>=511) { lcd.write(4); } else
       if (right[band]>=383) { lcd.write(3); } else
       if (right[band]>=255) { lcd.write(2); } else
       if (right[band]>=127) { lcd.write(1); } else
       if (right[band]>=0) { lcd.write(0); }
       }
      }

      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:

      // Example 48.3 - tronixstuff.com/tutorials > chapter 48 - 30 Jan 2013 
      // MSGEQ7 spectrum analyser shield with a Freetronics DMD
      // for DMD
      #include "DMD.h" // for DMD
      #include "SPI.h" // SPI.h must be included as DMD is written by SPI (the IDE complains otherwise)
      #include "TimerOne.h"
      #include "SystemFont5x7.h" // keep next two lines if you want to add some text
      #include "Arial_black_16.h"
      DMD dmd(1, 1); // creates instance of DMD to refer to in sketch
      void ScanDMD() // necessary interrupt handler for refresh scanning of DMD
      { 
       dmd.scanDisplayBySPI();
      }
      int strobe = 4; // strobe pins on digital 4
      int res = 5; // reset pins on digital 5
      int left[7]; // store band values in these arrays
      int right[7];
      int band;
      void setup()
      {
       // for DMD
       //initialize TimerOne's interrupt/CPU usage used to scan and refresh the display
       Timer1.initialize( 5000 ); //period in microseconds to call ScanDMD. Anything longer than 5000 (5ms) and you can see flicker.
       Timer1.attachInterrupt( ScanDMD ); //attach the Timer1 interrupt to ScanDMD which goes to dmd.scanDisplayBySPI() 
       dmd.clearScreen( true ); //true is normal (all pixels off), false is negative (all pixels on)
      
       // for MSGEQ7
       pinMode(res, OUTPUT); // reset
       pinMode(strobe, OUTPUT); // strobe
       digitalWrite(res,LOW); // reset low
       digitalWrite(strobe,HIGH); //pin 5 is RESET on the shield
      }
      void readMSGEQ7()
      // Function to read 7 band equalizers
      {
       digitalWrite(res, HIGH);
       digitalWrite(res, LOW);
       for( band = 0; band < 7; band++ )
       {
       digitalWrite(strobe,LOW); // strobe pin on the shield - kicks the IC up to the next band 
       delayMicroseconds(30); // 
       left[band] = analogRead(0); // store left band reading
       right[band] = analogRead(1); // ... and the right
       digitalWrite(strobe,HIGH); 
       }
      }
      void loop()
      {
       int xpos;
       readMSGEQ7();
       dmd.clearScreen( true ); 
       // display values of left channel on DMD
       for( band = 0; band < 7; band++ )
       {
       xpos = (band*2)+1;
       if (left[band]>=895) { dmd.drawLine( xpos, 15, xpos, 1, GRAPHICS_NORMAL ); } else
       if (left[band]>=767) { dmd.drawLine( xpos, 15, xpos, 3, GRAPHICS_NORMAL ); } else
       if (left[band]>=639) { dmd.drawLine( xpos, 15, xpos, 5, GRAPHICS_NORMAL ); } else
       if (left[band]>=511) { dmd.drawLine( xpos, 15, xpos, 7, GRAPHICS_NORMAL ); } else
       if (left[band]>=383) { dmd.drawLine( xpos, 15, xpos, 9, GRAPHICS_NORMAL ); } else
       if (left[band]>=255) { dmd.drawLine( xpos, 15, xpos, 11, GRAPHICS_NORMAL ); } else
       if (left[band]>=127) { dmd.drawLine( xpos, 15, xpos, 13, GRAPHICS_NORMAL ); } else
       if (left[band]>=0) { dmd.drawLine( xpos, 15, xpos, 15, GRAPHICS_NORMAL ); }
       }
      
       // display values of right channel on DMD
       for( band = 0; band < 7; band++ )
       {
       xpos = (band*2)+18;
       if (right[band]>=895) { dmd.drawLine( xpos, 15, xpos, 1, GRAPHICS_NORMAL ); } else
       if (right[band]>=767) { dmd.drawLine( xpos, 15, xpos, 3, GRAPHICS_NORMAL ); } else
       if (right[band]>=639) { dmd.drawLine( xpos, 15, xpos, 5, GRAPHICS_NORMAL ); } else
       if (right[band]>=511) { dmd.drawLine( xpos, 15, xpos, 7, GRAPHICS_NORMAL ); } else
       if (right[band]>=383) { dmd.drawLine( xpos, 15, xpos, 9, GRAPHICS_NORMAL ); } else
       if (right[band]>=255) { dmd.drawLine( xpos, 15, xpos, 11, GRAPHICS_NORMAL ); } else
       if (right[band]>=127) { dmd.drawLine( xpos, 15, xpos, 13, GRAPHICS_NORMAL ); } else
       if (right[band]>=0) { dmd.drawLine( xpos, 15, xpos, 15, GRAPHICS_NORMAL ); }
       }
      }

      … 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. 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: Arduino and the MSGEQ7 Spectrum Analyzer appeared first on tronixstuff.