t r o n i x s t u f f

fun and learning with electronics

Getting Started with Arduino! – Chapter Four

This is part of a series titled “Getting Started with Arduino!” – A tutorial on the Arduino microcontrollers. The first chapter is here, and the complete index is here.

Welcome back fellow arduidans!

In this chapter will be looking at getting more outputs from less pins, listening to some tunes, saying hooray to arrays, and even build a self-contained data logger!

So let’s go!

More pins from less – sounds too good to be true, doesn’t it? No, it is true and we can learn how to do this in conjunction with a special little IC, the 74HC595 Serial In/Parallel Out 8-bit Shift Register. Let’s say hello:

Before we get too carried away, we need to understand a little about bits, bytes and binary numbers.

A binary number can only uses zeros and ones to represent a value. Thus binary is also known as “base-2″, as it can only use two digits. Our most commonly used number types are base-10 (as it uses zero through to nine; hexadecimal is base-16 as it uses 0 to 9 and A to F). How can a binary number with only the use of two digits represent a larger number? It uses a lot of ones and zeros. Let’s examine a binary number, say 10101010. As this is a base-2 number, each digit represents 2 to the power of x, from x=0 onwards.

See how each digit of the binary number can represent a base-10 number. So the binary number above represents 85 in base-10 – the value 85 is the sum of the base-10 values.

Another example – 11111111 in binary equals 255 in base 10.

Now each digit in that binary number uses one ‘bit’ of memory, and eight bits make a byte. A byte is a special amount of data, as it matches perfectly with the number of output pins that the 74HC595 chip controls. (See, this wasn’t going to be a maths lesson after all). If we use our Arduino to send a number in base-10 out through a digital pin to the ’595, it will convert it to binary and set the matching output pins high or low.

So if you send the number 255 to the ’595, all of the output pins will go high. If you send it 01100110, only pins 1,2,5, and 6 will go high. Now can you imagine how this gives you extra digital output pins? The numbers between 0 and 255 can represent every possible combination of outputs on the ’595. Furthermore, each byte has a “least significant bit” and “most significant bit” – these are the left-most and right-most bits respectively.

Now to the doing part of things. Let’s look at the pinout of the 74HC595: (from NXP 74HC595 datasheet)

Pins Q0~Q7 are the output pins that we want to control. The Q7′ pin is unused, for now. ’595 pin 14 is the data pin, 12 is the latch pin and 11 is the clock pin. The data pin connects to a digital output pin on the Arduino. The latch pin is like a switch, when it is low the ’595 will accept data, when it is high, the ’595 goes deaf. The clock pin is toggled once the data has been received. So the procedure to get the data into a ’595 is this:

1) set the latch pin low (pin 12)

2) send the byte of data to the ’595 (pin 14)

3) toggle the clock pin (pin 11)

4) set the latch pin high (pin 12)

Pin 10 (reset) is always connected to the +5V, pin 13 (output enable) is always connected to ground.

Thankfully there is a command that has parts 2 and 3 in one; you can use digitalWrite(); to take care of the latch duties. The command shiftOut(); is the key. The syntax is:

shiftout(a,b,c,d);

where:

a = the digital output pin that connects to the ’595 data pin (14);

b = the digital output pin that connects to the ’595 clock pin (11);

c can be either LSBFIRST or MSBFIRST. MSBFIRST means the ’595 will interpret the binary number from left to right; LSBFIRST will make it go right to left;

d = the actual number (0~255) that you want represented by the ’595 in binary output pins.

So if you wanted to switch on pins 1,2,5 and 6, with the rest low, you would execute the following:

digitalWrite(latchpin, LOW);
shiftOut(datapin, clockpin, MSBFIRST,102);
digitalWrite(latchpin, HIGH);

Now, what can you do with those ’595 output pins? More than you could imagine! Just remember the most current you can sink or source through each output pin is 35 milliamps.

For example:

  • an LED and a current-limiting resisor to earth… you could control many LEDs than normally possible with your Arduino;
  • an NPN transistor and something that draws more current like a motor or a larger lamp
  • an NPN transistor controlling a relay (remember?)

With two or more ’595s you can control a matrix of LEDs, 7-segment displays, and more – but that will be in the coming weeks.

For now, you have a good exercise to build familiarity with the shift-register process.

Exercise 4.1

Construct a simple circuit, that counts from 0~255 and displays the number in binary using LEDs. You will require the following:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • 8 LEDs of your choosing
  • One 74HC595 shift register
  • 8 x 560 ohm 0.25 W resistors. For use as current limiters between the LEDs and ground.
  • a breadboard and some connecting wire

The hardware is quite easy. Just remember that the anodes of the LEDs connect with the ’595, and the cathodes connect to the resistors which connect to ground. You can use the Arduino 5V and GND.

Here is what my layout looked like:

and of course a video – I have increased the speed of mine for the sake of the demonstration.

How did you go? Here is the sketch if you need some ideas.

Next on the agenda today is another form of output – audio.

Of course you already knew that, but until now we have not looked at (or should I say, listened to) the audio features of the Arduino system. The easiest way to get some noise is to use a piezo buzzer. An example of this is on the left hand side of the image below:

These are very simple to use and can be very loud and annoying. To get buzzing, just connect their positive lead to a digital output pin, and their negative lead to ground. Then you only have to change the digital pin to HIGH when you need a buzz. For example:

/* Example 4.1
Annoying buzzer!
CC by-sa v3.0
http://tronixstuff.wordpress.com */
void setup()
{
pinMode(12, OUTPUT);
}
void loop()
{
digitalWrite(12, HIGH);
delay(500);
digitalWrite(12, LOW);
delay(2000);
}

You won’t be subjected to a recording of it, as thankfully (!) my camera does not record audio…

However, you will want more than a buzz. Arduino has a tone(); command, which can generate a tone with a particular frequency for a duration. The syntax is:

tone(pin, frequency, duration);

where pin is the digital output pin the speaker is connected to, frequency in Hertz, duration in milliseconds. Easy!

If you omit the duration variable, the tone will be continuous, and can be stopped with notone();. Furthermore, the use of tone(); will interfere with PWM on pins 3 and 11, unless you are using an Arduino Mega.

Now, good choice for a speaker is one of those small 0.25w 8 ohm ones. My example is on the right in the photo above, taken from a musical plush toy. It has a 100 ohm resistor between the digital output pin and the speaker. Anyhow, let’s make some more annoying noise – hmm – a siren! (download)

/* Example 4.2
Annoying siren
CC by-sa v3.0
http://tronixstuff.wordpress.com */
void setup()
{
pinMode(8, OUTPUT); // speker on pin 8
}
int del = 250; // for tone length
int lowrange = 2000; // the lowest frequency value to use
int highrange = 4000; //  the highest...
void loop()
{
// increasing tone
for (int a = lowrange; a<=highrange; a++)
{
tone (8, a, del);
}
// decreasing tone
for (int a = highrange; a>=lowrange; a--)
{
tone (8, a, del);
}
}

Phew! You can only take so much of that.

Array! Hooray? No… Arrays.

What is an array?

Let’s use an analogy from my old comp sci textbook. Firstly, you know what a variable is (you should by now). Think of this as an index card, with a piece of data written on it. For example, the number 8. Let’s get a few more index cards, and write one number on each one. 6, 7, 5, 3, 0, 9. So now you have seven pieces of data, or seven variables. They relate to each other in some way or another, and they could change, so we need a way to keep them together as a group for easier reference. So we put those cards in a small filing box, and we give that box a name, e.g. “Jenny”.

An array is that small filing box. It holds a series of variables of any type possible with arduino. To create an array, you need to define it like any other variable. For example, an array of 10 integers called jenny would be defined as:

int jenny[10];

And like any other variable, you can predefine the values. For example:

int jenny[10] = {0,7,3,8,6,7,5,3,0,9};

Before we get too excited, there is a limit to how much data we can store. With the Arduino Duemilanove, we have 2 kilobytes for variables. See the hardware specifications for more information on memory and so on. To use more we would need to interface with an external RAM IC… that’s for another chapter down the track.

Now to change the contents of an array is also easy, for example

jenny[3] = 12;

will change our array to

int jenny[10] = {0,7,3,12,6,7,5,3,0,9};

Oh, but that was the fourth element! Yes, true. Arrays are zero-indexed, so the first element is element zero, not one. So in the above example, jenny[4] = 6. Easy.

You can also use variables when dealing with arrays. For example:

for (int i = 0; i<10;  i++; i<10)
{
jenny[i] = 8;
}

Will change alter our array to become

jenny[] = {8,8,8,8,8,8,8,8,8,8}

A quick way set set a lot of digital pins to output could be

int pinnumbers [] = {2,3,4,5,6,7,8,9,10,11,12,13}
for (int i= 0; i++; i<12)
{
pinMode(pinnumbers[i],OUTPUT);
}

Interesting… very interesting. Imagine if you had a large array, an analogue input sensor, a for loop, and a delay. You could make a data logger. In fact, let’s do that now.

Exercise 4.2

Build a temperature logger. It shall read the temperature once every period of time, for 24 hours. Once it has completed the measurements, it will display the values measured, the minimum, maximum, and average of the temperature data. You can set the time period to be of your own choosing. So let’s have a think about our algorithm. We will need 24 spaces to place our readings (hmm… an array?)

  • Loop around 24 times, feeding the temperature into the array, then waiting a period of time
  • Once the 24 loops have completed, calculate and display the results on an LCD and (if connected) a personal computer using the Arduino IDE serial monitor.

I know you can do it, this project is just the sum of previously-learned knowledge. If you need help, feel free to email me or post a comment at the end of this instalment.

To complete this exercise, you will need the following:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Water (you need to stay hydrated)
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • 1 little push button
  • 1 x 10k 0.25 W resistor. For use with the button to the arduino
  • a breadboard and some connecting wire
  • one LCD display module

And off you go!

Today I decided to construct it using the Electronic Bricks for a change, and it worked out nicely.

Here is a photo of my setup:

a shot of my serial output on the personal computer:

and of course the ubiquitous video. For the purposes of the demonstration there is a much smaller delay between samples…

(The video clip below may refer to itself as exercise 4.1, this is an error. It is definitely exercise 4.2)

And here is the sketch if you would like to take a peek. High resolution photos are available in flickr.

Another chapter over! I’m already excited about writing the next instalment… Chapter Five.

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

April 30, 2010 Posted by | 74hc595, arduino, education, microcontrollers, tutorial | , , , , , , , , , , , , , , | 15 Comments

Kit Review – Seeedstudio Electronic Brick Starter Kit

If you have been directed here for a tutorial, please download this ebook: Electronic Brick Getting Started Guide.pdf

[Updated 17/01/2013]

Time for another kit review. Well, perhaps not a kit, but an educational system designed for a beginner to start doing things, fun and educational things, with an Arduino. From Seeedstudio comes their “Electronic Brick” Starter Kit. What on earth could this be all about, you ask?

Imagine a system of components, that connect together easily, can be reused, to work with an Arduino Uno or compatible – allowing you to experiment, learn and rapidly prototype projects with ease and safety… This is it!

Sort of like electronic LEGO for Arduino…

Let’s have a look…

First of all, it comes in a nice box, keeping all the goodies safe and sound. Although an Arduino board nor USB cable is included, they could also fit inside this box in a pinch.

But what are all these things in there? The “bricks” are basically little PCBs with a particular component mounted on it, an interface circuit if necessary, and a connector that matches the wires included in the starter kit.

From left to right, top to bottom, we have: a terminal block to interface with a pair of wires, a push button, a piezo buzzer, a potentiometer, a light-dependent resistor, a green LED, a tilt switch (bearing in a tube, not mercury), a temperature sensor (using a thermistor) and a red LED.

Furthermore, there is a 16×2 character backlit LCD…

And the major part, the chassis…

The chassis is an arduino shield that extends analogue pins 1~5, digital pins 8-12, the UART and I2C connections. Furthermore, there are three large ten-pin connectors in the centre called “Bus” connections. Each is different, extending a variety of digital/analog pins out. For example, BUS2 consists of digital pins 10~16, power and ground. This allows a direct connection to the LCD screen leaving other pins free for use.

An example project is shown below…

You can see how the chassis shield sits on the Arduino, and the chassis is connected to the LCD module, the potentiometer and an LED. The benefits of this “brick” system are many – for me the greatest thing was the size of the bricks are not too small, and quite strong. They would stand up to quite a beating, which would be good for a classroom setting, a family of enthusiastic arduidans, or just people who are hard on things.

There is no difference to the arduino sketch when  you are using this system, so if you do create a prototype and wish to move further with your project, you only have to change a few pin locations if you decide to use the LCD or input/outputs on other pins. So you don’t have to rewrite your code – neat. As an example, I tested it with my random number sketch from “Getting Started with Arduino” chapter two – all I had to do was change the pins in the LiquidCrystal command. Let’s see how that went, here is the sketch

#include <LiquidCrystal.h> // we need this library for the LCD commands
LiquidCrystal lcd(10,11,12,13,14,15,16);
float noisy = 0;
void setup()
{
lcd.begin(16, 2);             // need to specify how many columns and rows are in the LCD unit
lcd.println("tronixstuff!    ");
lcd.setCursor(0,1);
delay(2000);
lcd.clear();
randomSeed(analogRead(0)); // reseed the random number generator with some noise
}
void loop()
{
noisy=random(1000);
lcd.setCursor(0,0);
lcd.print("Random Numbers!");
lcd.setCursor(0,1);
lcd.print("Number: ");
lcd.print(noisy,0);
delay(1000);
}

and the video:

And then some fun with the temperature sensor, the sketch:

#include <LiquidCrystal.h>
// we need this library for the LCD commands
LiquidCrystal lcd(10,11,12,13,14,15,16);
void setup()
{
lcd.begin(16, 2); // tells Arduino the LCD dimensions
lcd.setCursor(0,0);
lcd.print("Hello electropus!");
// print text and move cursor to start of next line
lcd.setCursor(0,1);
lcd.print("Please wait...");
delay(2000);
lcd.clear(); // clear LCD screen
lcd.setCursor(0,0);
lcd.print("Temperature is ");
}
float temperature = 0;
void loop()
{
temperature = analogRead(5); // store value from temp brick
temperature = temperature +252-500;
temperature = temperature / 10;
delay (100); // wait for 100 milliseconds
lcd.print(" Temperature is    ");
lcd.setCursor(0,1);
lcd.print(temperature);
lcd.println(" deg. C.   ");
delay(1000); // wait a second
}

and the video:

So there you have it. This is a simple, yet empowering way of experimenting and learning with the Arduino system. I do recommend this for beginners, or people who don’t want to muck about with tiny components. This in conjunction with an Arduino board would make a great gift for the technically-minded person of almost any age. The manufacturer is working on more bricks, and they should be released shortly.

The Electronic Brick is available from Seeedstudio, and Little Bird Electronics in Australia. High resolution photos are available on flickr.

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.

April 28, 2010 Posted by | arduino, education, kit review, LCD, learning electronics, microcontrollers | , , , , , , , , , , , , | Leave a Comment

Amazing and useful Arduino Cheat Sheet!

The Mechatronics Guy has created a wonderful sheet containing everything you will need to know about Arduino. Constants, control structures, libraries, pin layouts – everything!

Click here to download a full-size copy…

If you are interested in all things Arduino, we have a weekly Arduino tutorial which is fun, easy and interesting. The first chapter starts here.

April 27, 2010 Posted by | arduino, education | , , , , , , , , , , , | 4 Comments

Getting Started with Arduino! – Chapter Three

This is chapter three of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – in what feels like an endless series of articles on the Arduino universe. The first chapter is here, the complete series is detailed here. Any files from tutorials will be found here.

[Updated 09/01/2013]

In this chapter we will be looking at relays, creating your own functions, interrupts, and servos.

First on the agenda to day are relays.

What is a relay? Think of it as two things that are very close together: a coil that sometimes has a current passing through it; and a switch, that defaults in one direction. When a current passes through the coil, it generates an electromagnetic field which causes the switch to change state. The beauty of a relay is this: you can use a small current and voltage to switch on and off a very large current and/or voltage – and the switch and coil current are isolated from each other. Here is an example of a relay:

If you look closely you can see the coil and the internals of the switch. This particular model has a double-pole, double throw switch. That means two inputs can be switched in either of two directions. The coil needs 12 volts to activate; and the switch can handle 250 volts AC at 5 amps; and the coil resistance is 200 ohms. Ohm’s law (voltage = current x resistance) tells us the coil current is 60mA. No way you can get that sort of current out of an arduino – hence the need for a relay. (Though if anyone wants to try, stand back and film it for us!) The only problem with relays is that they contain moving parts (the switch) and hence will wear out over time. So if you design a relay into a project, be sure to document a maintenance schedule for the end-user or maintenance people.

How will we use this with our arduino? Once again – very easily. But we need a partner in our relay quest – a switching transistor. A simple, garden-variety NPN model will do, such as the BC548. However, when selecting your transistor you need to ensure that it can handle the current of the relay coil. The data sheet for your transistor (e.g. our BC548) will mention a value called Ic – collector current. For our BC548 this is 100mA, and greater than the 60mA of our relay coil. Perfect!

Almost there… when a coil switches off, all the electromagnetic radiation in the coil needs to go somewhere, otherwise it could pulse down into the transistor. Therefore a simple 1A power diode (such as a 1N4004) is placed across the coil, allowing current to flow through the coil and the diode as a loop until it dissipates.

The last thing to verify is the relay coil voltage. If you have a 5V relay, with a low coil current, you can use the arduino power. However in most cases your coil voltage will be 12V, so it will require its own power supply.

Here is the schematic for what you should end up with, using a 12V relay and a low current transistor. Although it isn’t shown in the schematic, connect the GND from the 12V supply to the Arduino GND.  Since writing this article I have found some 5V relays are available, negating the 12v power supply requirement:

So now for a simple test to get a feel for the operation of a relay… here is our sketch: (download)

// example 3.1

void setup()
{ 
  pinMode (2, OUTPUT); // set pin 2 as an output pin
} 

void loop()
{ 
  for (int i = 1; i<=20; i++) // loop 20 times
  { 
    digitalWrite (2, HIGH); // turn on pin2 for 1 second, then off for one second
    delay (1000);
    digitalWrite (2, LOW);
    delay (1000);
  }
  delay (2000);
}
 Our hardware is exactly as the schematic above. Here is a photo:
 
 

And of course a video. Here you can see in detail the coil causing the switch to change poles.


 
 

From here on you understand and can use an arduino to switch a very high current and/or voltage. Please exercise care and consult an expert if you are working with mains voltage. It can KILL you.

Creating your own functions…

There are three main components to an arduino sketch: the variables, the structure and the functions. Functions are the commands that request something to happen, for example analogRead();. You can also define your own functions to improve the structure and flow of your sketch. If you have previous programming experience, you may think of these as sub-procedures, or recall using GOSUB in BASIC all those years ago. An ideal candidate for a custom function would be exercise 2.2 from our last instalment – we could have written functions to organise the min/max display or reset the memory. However, first we must learn to walk before we can run…

Do you remember void loop(); ? I hope so – that is the function that defines your sketch after the setup. What it really does is define the code within into a loop, which runs continuously until you reset the arduino or switch it off. You can simply define your own functions using the same method. For example:

void blinkthree()  // the name of my function is "blinkthree"
{
for (int i = 0; i <3; i++) // loop three times
{
digitalWrite(8, HIGH); // turn on LED connected to digital pin 8
delay (1000);
digitalWrite(8, LOW); // turn off LED connected to digital pin 8
delay (1000);
}
}

Now that function has been defined, when you want to blink the LED on pin 8 three times, just insert void blinkthree(); into the required point in your sketch. But what if you want to change the number of blinks? You can pass a parameter into your function as well. For example:

void blinkblink(int blinks)  // the name of my function is "blinkblink", and receives an integer which is stored in the variable blinks
{
for (int i = 0; i <blinks; i++) // loop "blinks" times
{
digitalWrite(8, HIGH); // turn on LED connected to digital pin 8
delay (1000);
digitalWrite(8, LOW); // turn off LED connected to digital pin 8
delay (1000);
}
}
So to blink that LED 42 times, execute blinkblink(42); Want to specify your own delay? Try this:
void blinkblink(int blinks, int del)  // the name of my function is "blinkblink", and receives an integer which is stored in the variable blinks, and another del ...
{
for (int i = 0; i<blinks; i++) // loop "blinks" times
{
digitalWrite(8, HIGH); // turn on LED connected to digital pin 8
delay (del);
digitalWrite(8, LOW); // turn off LED connected to digital pin 8
delay (del);
}
}
So to blink that LED 42 times, with an on/off period of 367 milliseconds – execute blinkblink(42,367);. It is quite simple, don’t you think?
Ok, one more. Functions can also function as mathematical functions. For example:
float circlearea (float radius)
{
float result = 0;
result = 3.141592654 * radius * radius;
return result;
}

Do you see what happened there? If our sketch determined the radius of a circle and placed it in a variable radius2, the area of the circle could be calculated by:

area2 = circlearea(radius2);

Easy.

So now you can create your own functions. Not the most colourful of sections, but it is something we need to know.

Time for a stretch break, go for a walk around for five minutes.

Interrupts…

An interrupt is an event that occurs when the state of a digital input pin changes, and causes a specific function to be called and its contents to be executed.

For example, a robot… while it is happily wandering about a sensor is monitoring a proximity sensor pointing to the ground, which changes state when the robot is lifted off the ground and triggers an interrupt – which could switch off the wheels or sound an alarm (“Help, I’m being stolen!”). I am sure your imagination can think of many other things.

So how do we make an interrupt interrupt? It is relatively easy, with a couple of limitations. You can only monitor two pins (for a normal arduino board) or six with an Arduino mega. Furthermore, you cannot use the function delay() in your interrupt function. Now, you need to decide three things: the pin to monitor (digital 2 or 3, referred to as 0 or 1), the function to run when the interrupt occurs, and what sort of behaviour to monitor on the interrupt pin – that is, the change of state of the pin. Your pins also need to be set to output using pinMode();.

There are four changes of state: LOW (when the pin becomes low), CHANGE (when the pin changes state, from high or from low), RISING (when pin goes from low to high) and FALLING (when pin goes from high to LOW). Initially that looks like  a lot to remember, but it is quite simple when you think about it.

Crikey – that was a lot to take in. So instead of theory, it is time for some practice.

Example 3.2 – interrupt demonstration.

In this example, we will have our random number generator from example 2.2, but with two interrupts being monitored. These will be triggered by push buttons for simplicity: (download)

// Example 3.2 – interrupts

#include <LiquidCrystal.h> // we need this library for the LCD commands

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

float noisy = 0;

void setup()
{
  lcd.begin(16, 2);             // need to specify how many columns and rows are in the LCD unit
  lcd.setCursor(0,0);
  lcd.println('* example 3.2 * ');
  lcd.setCursor(0,1);
  lcd.println('tronixstuff.com ');
  lcd.setCursor(0,1);
  delay(4000);
  lcd.clear();
  randomSeed(analogRead(0)); // reseed the random number generator with some noise
  attachInterrupt(0, panicone, RISING); // so when interrupt zero (digital pin 2) changes state, it will trigger the interrupt and go to function 'panicone'
  attachInterrupt(1, panictwo, RISING); // so when interrupt one (digital pin 3) changes state, it will trigger the interrupt and go to function 'panictwo'
}

void loop()
{
  noisy=random(1000);
  lcd.setCursor(0,0);
  lcd.print('Random Numbers!');
  lcd.setCursor(0,1);
  lcd.print('Number: ');
  lcd.print(noisy,0);
  delay(1000);
}

void panicone()
{
  lcd.clear();
  lcd.println('Interrupt one   ');
}

void panictwo()
{
  lcd.clear();
  lcd.println('Interrupt two   ');
}

Of course it wouldn’t be right without a photo of the board layout – we have just reused the LCD set-up from example 2.2, and added two standard push-buttons and 10k resistors (as per page 42 of the book) for the interrupts. Here you are:

And the video… those switches could really have used a de-bounce circuit, but for the purpose of the demonstration they are not really necessary.

Finally – it’s servo time! I really hope you went through the other sections before heading here – although they may not have been that interesting, they will certainly be useful.

What is a servo?

Think of a little electric motor that is connected to a variable resistor. An electric pulse or command is sent to the motor, and it rotates until it reaches a position that matches a value of the potentiometer. Yes, that sounds a little crazy.

A much simpler explanation is this: a servo is an electric motor that can be commanded to rotate to a specific angular position. For example, they are commonly used to control the steering in a remote-control car. Thankfully once again with arduino and friends, using a servo is very easy, and allows your imagination to go nuts, limited only by the amount of spare time and money you have. :)

When considering the use of a servo, several factors need to be taken into account. These include:

  • rotational range, that is the angular range it can rotate. 180 degrees, 360 degrees (full rotation), etc.
  • the speed at which it can rotate (usually measured in time per degrees)
  • the torque the servo can generate (how strong it is)
  • the amount of current it draws under load
  • weight, cost, and so on

One of the first things that came to mind was “Wow – how many can I use at once?” And the answer is … 12 on the Duemilanove/Uno, and 48 (wow) on the Arduino Mega. Please note you cannot used analogWrite(); on pins 9 and 10 when  using the servo library. For more details, please see the Arduino servo library page. However you will need to externally power the servos (as we did with the 12V relay) for general use. And as always, check the data sheet for your servo before use.

For our examples and exercises today, I am using the Turnigy TG9. It is quite inexpensive and light, good for demonstration purposes and often used in remote control aircraft.  It can rotate within a range of almost 180 degrees (well it was cheap).

I hope you noticed that there are three wires to the servo. One is for +5V, one is for GND, and one is the control pin – connect to an arduino digital out. Which colour is which pin may vary, but for this servo, the darkest is GND, the lightest is control, and the middle colour is the +5V. This servo is very small and doesn’t draw much current, so it’s ok to power from your Arduino board. However, if using something larger, or putting your servo under load – as mentioned earlier you will need to run it from a separate power supply that can deliver the required current. If working with more than a couple of these light-duty servos, you should get an external power supply. Moving forward, when working with angles, you should have a protractor handy. Such as:

Now how do we control our servo? First of all, we need to use the servo library. In the same manner as we did with the LCD screen in chapter two, place the following line at the start of your sketch:

#include <Servo.h>

So now we have access to a range of servo commands.

Then you need to create the servo object in your sketch, so it can be referred to, such as

Servo myservo;

Then finally, attach the servo to a digital pin for control (within your void(setup); )

myservo.attach(9);  // attaches the servo on pin 9 to the servo object

That is the setting up out of the way. Now all you need to do is this…

myservo.write(pos);

where pos is a value between 0 and 180. (or more or less, depending on the rotational range of your servo).

Now, the proof is in the pudding so to speak, so here once more is an example of it all coming together and rotating. :) The following example moves from left to middle to right and repeats, to give you an idea of what is happening: (download)

// Example 3.3 – servo examination

#include <Servo.h>
Servo myservo;  // create servo object to control a servo

int pos = 0;    // variable to store the servo position
int del = 100; // delay in micoseconds

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for (int loopy = 0; loopy<=3; loopy++)
  {
    for (pos = 180; pos >=0; pos--) // from left to right with Hextronik HXT900
    {
      myservo.write(pos);
      delay(del);
    }
    delay(1000);
  }
  for (int loopy = 0; loopy<=3; loopy++)
  {
    myservo.write(180);
    delay (1000);
    myservo.write(90);
    delay (1000);
    myservo.write(0);
    delay (3000);
  }
}

The board layout is quite simple, just the three servo wires to the arduino board.

And the video. The camera does not record audio, so you cannot hear the cute buzz of the servo.

Ok then – that’s enough reading and watching from your end of the Internet. Now it is time for you to make something; using all the knowledge that we have discussed so far…

Exercise 3.1

We can use our digital world to make something useful and different – an analogue digital thermometer, with the following features:

  • analogue temperature display over a 180-degree scale. The range will vary depending on your home climate. My example will be 0~40 degrees Celsius
  • analogue meter showing whether you can have the heater or air-conditioner on, or off. A rendition of exercise 2.1 in analogue form.
  • minimum and maximum temperature display, displayable on demand, with indicators showing what is being displayed (LEDs would be fine); and a reset button

You will need to combine your own functions, working with temperature sensors; a lot of decision-making, digital and analogue inputs, digital and analogue outputs, and some creativity. To reproduce my example of the exercise, you will need the following:

  • Your standard Arduino setup
  • Water (you need to stay hydrated)
  • Analog Devices TMP36 temperature sensor
  • 2 little push buttons
  • 2 x 10k 0.25 W resistors. They work with the buttons to the arduino
  • a breadboard and some connecting wire
  • two LEDs to indicate minimum/maximum
  • 2 x 390 ohm 0.25 W resistors. They are to reduce the current to protect the LEDs.

So off you go… if you have any questions, leave a comment at the end of the post, or email john at tronixstuff dot com.

And now for the results of the exercise. Here are photos of my board layout:

Here you can see the buttons for displaying minimum/maximum temperature, and the reset button. The LEDs indicate the right servo is display minimum or maximum temperature, or illuminate together to ask if you want to reset the memory. And of course, our video:

And here is the sketch for my example board layout. Congratulations to all those who took part and built something useful. Now to move on to Chapter Four.

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.

April 20, 2010 Posted by | arduino, microcontrollers, relay, servo, tutorial | , , , , , , , , , , , , , | 3 Comments

Part Review – Peter H. Anderson Serial LCD Controllers

Hello interested readers

Today we are going to examine a part that makes using LCD modules much easier to interface with microcontrollers – a serial LCD controller IC. Note that this is designed for LCD modules with the standard Hitachi HD44780 interface (almost all LCD modules…) Normally your LCD module would interface with a controller using a 4- or 8-bit parallel interface. In fact, we have done this in chapter of the arduino tutorial here. However in some cases, you may need the digital output pins on your controller for other uses, which can be frustrating. With a serial LCD interface, you only need one serial out port, your +5V power supply and some space on the board for another IC. Therefore it is very easy for even the smallest microcontroller, such as an 8-pin PICAXE -08M to control an LCD. Who would have thought a little micro could push an LCD?

Moving on, a gentleman in the US by the name of Peter H. Anderson has developed his own serial LCD module controller IC using a Microchip PIC16F648A and his own custom software.  First of all, let’s say hello.

Peter also offers these in a surface mount SOIC-18 profile in bulk amounts. Great for those projects that hit a successful market.

If you had an Arduino Mega, with 4 serial out pins – you could run 4 LCD modules at once. That would be interesting…

Consider the following image, the only pin used on the arduino is TX (serial out). The other two are GND and 5V, as it is being powered from the breadboard PSU.


Unsurprisingly the software for these chips is not open source, however the purchase price is more than outweighed by the convenience that they offer the user. Peter has created some simple commands to control the LCD – which are just sent as serial output text, including:

?a - set cursor to home position.
?b - destructive backspace
?f - clear LCD and leave cursor at home position
?g - beep
?h - backspace
?i - forward cursor
?j - up cursor
?k - down cursor
?l - clear current line and leave cursor at the beginning of the line
?m - carriage return.  Position the cursor at the beginning of the current line.
?n - new line.  Advance to the beginning of the next line and clear this line.
?t - tab.  Advance the cursor one tab.
?? - display the character '?'.

More command examples can be found here. With the right circuitry (detailed in the website) you can also control the back light brightness. You can even create jumbo-sized numbers if you have a four line LCD moduleThe chip does remove a lot of hard work for the user on the software side, however does require some hardware for itself. Sending commands and data to the LCD is as easy as a serial write command, for example with arduino:
/*
Arduino demo sketch using Peter H. Anderson serial LCD chip - http://www.phanderson.com
by John Boxall - http://tronixstuff.wordpress.com - 19/04/2010
*/
float noisy = 0;
void setup()
{
Serial.begin(2400);    // am using 2400bps serial LCD chip, therefore this line is required
randomSeed(analogRead(0)); // reseed the random number generator with some noise
delay (5000);           // the serial LCD chip needs about five seconds to boot up
}
void loop()
{
// setup the chip parameters
Serial.print("?G216");  // define the LCD as 2 rows by 16 characters
delay (1000);            // need a delay between each instruction to the serial LCD chip
Serial.print("?C0tronixstuff.com "); // next two define the boot-up message displayed. This can also be delayed on call using "?*"
delay (1000);
Serial.print("?C1* part review * "); // you need to fill the entire 16 characters
delay (1000);
Serial.print("?S2"); // chip will display boot message every time it is reset
delay (1000);
Serial.print("?*"); // display boot message as defined above
delay (5000);
// now some displaying...
for (int j = 1; j<9999; j++)
{
Serial.print("?f"); //clear the screen
delay (500);
Serial.print("all your base");
delay (500);
Serial.print("?n"); // move cursor to start of next line
delay(1000);
Serial.print("... belong to us");
delay (2000);
Serial.print("?f"); //clear the screen
delay (500);
Serial.print("?*"); // display boot message as defined above
delay (5000);
Serial.print("?f"); //clear the screen
delay (500);
// display some random numbers
Serial.print("Random Numbers!");
Serial.print("?n"); // move cursor to start of next line
for (int i = 1; i<5; i++)
{
noisy=random(1000);
Serial.print("Number: ");
Serial.print(noisy,0);
delay (1000);
Serial.print("?m"); // move cursor to start of the current line
}
Serial.print("?f"); //clear the screen
delay (500);
Serial.print("?*"); // display boot message as defined above
delay (5000);
Serial.print("?f"); // clear screen
Serial.print("Earth");
delay(500);
Serial.print(".");
delay(500);
Serial.print(".");
delay(500);
Serial.print(".");
delay(500);
Serial.print("?n"); // move cursor to start of next line
delay(500);
Serial.print("Mostly harmless");
delay(5000);
}
}
or with PICAXE:
main:' LCD test with phanderson.com seral controller chip -  23/03/2010
wait 5 ' it takes a moment for the chip to boot and the LCD to wake up
'serout 2, T2400, ("?S2") ' show my copyright message [as shown below] at boot
'wait 1
'serout 2, T2400, ("?f") ' clear screen
'wait 1
'serout 2, T2400, ("?c0") ' turns off blinking cursor
'wait 1
'serout 2, T2400, ("?C0copyright 2010  ") ' set top line of initial boot message
'wait 1
'serout 2, T2400, ("?C1tronixstuff.com ") ' set bottom line of initial boot message
'wait 3
serout 2,T2400,("Hello. I hope")
serout 2, T2400, ("?n")
serout 2, T2400,("that this works")
wait 3
serout 2, T2400, ("?f") ' clear screen
serout 2, T2400, ("?*") ' show boot message
wait 3
serout 2, T2400, ("?f")  'clear screen
serout 2, T2400, ("Close the fridge")' as this is 16 characters, you can keep sending characters and the LCD will auto scroll to the next line
serout 2, T2400, ("door now please!") '
wait 3
serout 2, T2400, ("?f") ' clear screen completely for next text display
goto main
end

Here is a video clip of the arduino example (no audio):

More code examples are available on Peter’s web site. So a short and sweet review, but a good product that will make a complex task quite easy.

Please subscribe (see the top right of this page) to receive notifications of new articles. If you have any questions at all please leave a comment (below).

[Note - these parts were purchased by myself personally and reviewed without notifying the manufacturer or retailer]

April 20, 2010 Posted by | LCD, part review | , , , , , , , , , , , , , | Leave a Comment

Kit Review – adafruit industries SIM reader (part one)

[Updated 18/03/2013]

In this review will cover another the SIM reader from adafruit industries.

The result of this kit is a device that can read the data from a GSM SIM card, such as last-dialled numbers, SMS messages, the phone book, and so on. Although this may not sound like much, the concept of having this sort of technology at home really is amazing; that is – you can learn about the GSM SIM technology and hack into it.

The kit was shipped to me via USPS First Class International postage – taking five days to arrive in Australia from New York. Frankly that’s good enough and therefore no need for a courier.

adafruit also set the standard with customs paperwork, with a full and honest declaration inside and out. By doing this I feel it speeds the parcel through Customs… a lot quicker than those packages from Chinese eBay sellers who always put “Gift, US$2″ on everything. Opening up reveals the kit itself, in an anti-static resealable bag. Groovy, packaging I can reuse and not throw away…

Another smart move is to not include paper instructions, instead having a very detailed web site and a busy support forum. You can always print the instructions out if you don’t have a PC in your work area. The next thing I love to do is have a look at the components, and get a feel for the kit itself.

What stands out with adafruit kits compared to most others (I’m looking at you, Jaycar) is the quality of components. A decent PP3 battery snap that won’t break when you are tired and cranky, branded semiconductors, and a beautiful solder-masked, silk screened PCB. However, no IC socket. Grr. However, one can tell this has been designed by an enthusiast and not some bean-counter.

But that’s enough looking and talking – let’s build it…

My advice at this point is to check you have all the components on hand, and then line them up in order to make it easier while you are soldering. There was also a couple of parts that missed their photo shoot call…


If possible, the best way to make adafruit kits is to have your computer in front of you, as you can follow the detailed instructions as you go along. With the instructions up on the screen, the helping hands ready, the fume extractor on, and the tools at my side – it’s time to get cracking.

First the resistors, protection diode, LED and PP3 snap  …

Time for a quick test (excellent for confidence-building and troubleshooting) …

Excellent, the LED is working. The rest of the components are easily soldered… as there was no IC socket I soldered opposing pins in order to spread the heat load. The second-last part to fit was the SIM card reader. This had me worried, as if it was damaged, it would take a few days to replace. However, the instructions made it look simple – and it was. Taking a decent photo of it was more difficult…

And finally, the last part – DB9 fitting for the serial cable to the PC. The kit is supplied with a female connector… but silly me ordered the wrong serial cable, so I am using a male connector. Again, this was easy to fit – the PCB slid between the two rows of pins on the plug, and had large solder pads to make a good strong connection.

OK – we’re done. Now for a SIM card… Ms. Tronixstuff wouldn’t volunteer hers, so mine will be the first victim…

Now time to install the psySIMReader software. It is freely available here with instructions.  Originally my first attempt was with Ubuntu 9.1 and 10.04, but there were too many python errors, and I wasn’t in the mood for learning another language. Eventually I learned how to force the python software to look at COM1 – a good start. But no go – the zero error. Off to a windows xp machine. Seemed ok, but when I attempt to open the COM1 port an error says something about returning zero. This could possibly mean my SIM card is non-standard. *sigh* Went to the supermarket and bought a Vodafone SIM for $2, maybe they are different to my Virgin mobile SIM in some way. On the way back I stopped in again and tried the whole process on the windows xp machine, same error. Vodafone SIM card didn’t work either. Zero for both.

So home again. After reading the support forums, I resoldered all the joints, checked for continuity around the board, reinstalled python and the software, zero error again. Maybe SIM cards have changed a little since the kit was introduced? Then I looked at my serial cable – 3 metres. Perhaps it was too long? So I chopped off one end leaving about 150mm and soldered up another DB9 plug.

Tested the cable, tried again – still the zero error.

Another trawl through the forums and google revealed people having the same zero error, but it being fixed with a resolder job and/or plugging the PCB straight into the serial port on the computer. I cannot do this having originally soldered on a DB9 male to the PCB. Argh. Either it is my soldering or my dodgy serial cable hackup. Soon I will order up an FTDI cable, have someone else check my soldering with better eyes, and then try connecting again.

So at this stage, the verdict is still out. However, I must commend adafruit industries as a great organisation with respect to ordering, speed of delivery, quality and amount of detail on the website, and the support and enthusiasm offered throughout. Their other products have all received rave reviews and are supported much more than adequately.

At this point I will finish part one of the review, and return when the FTDI cable arrives.

[edit] – Click here to visit part two of this review.  High resolution photos are available on flickr.

[Note - this kit was purchased by myself personally and reviewed without notifying the manufacturer or retailer]

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

April 19, 2010 Posted by | adafruit, cellphone hacking, GSM, kit review, learning electronics | , , , , , , , , , , , , , | Leave a Comment

Getting Started with Arduino! – Chapter Two

This is part of a series titled “Getting Started with Arduino!” – A tutorial on the Arduino microcontrollers, to be read with the book “Getting Started with Arduino” (Massimo Banzi). The first chapter is here.

Welcome back fellow arduidans!

I hope you have been enjoying these posts and learning and creating and making many things. If not, you soon should be!

Today’s post has several things: taking temperatures, sending data from the arduino back to your PC, opening a library, and some exercises that will help to consolidate your previous knowledge and help revise it.

Note – Using LCD screens has moved to Chapter 24.

First of all, we shall investigate another analogue sensor – a temperature sensor. As you can imagine, there are many applications for such a thing, from just telling you the current temperature, to an arduino-based thermostat control system. And it is much easier to create than most people would think – so get ready to impress some people!

Let’s say hello to the Analog Devices TMP36 Low-voltage temperature sensor:


Tiny, isn’t it? It looks just like a standard transitor (e.g. a BC548) due the use of the same TO-92 case style. The TMP36 is very simple in its use – looking at the flat face, pin 1 is for +5V supply (you can connect this to the 5V socket on your arduino), pin 2 is the output voltage (the reading), and pin three is ground/earth (connect this to the GND socket on your arduino). Furthermore, have a look at the data sheet, it is quite easy to read and informative. TMP36 data sheet

The TMP36 will return a voltage that is proportional to temperature. 10 mV for each degree Celsius, with a range of -40 to 125 degrees.

There isn’t any need for extra resistors or other components – this sensor must be the easiest to use out there. However there is one situation that requires some slight complexity – remote positioning of the sensor. It is all very well to have the sensor on your breadboard, but you might want it out the window, in your basement wine cellar, or in your chicken coop out back… As the voltage output from the sensor is quite low, it is susceptible to outside interference and signal loss. Therefore a small circuit needs to be with the sensor, and shielded cable between that circuit and the home base. For more information on long runs, see page fifteen of the data sheet.

At this point we’re going to have some mathematics come into the lesson – sorry about that. Looking again at page eight of the data sheet, it describes the output characteristics of the sensor. With our TMP36, the output voltages increases 10 millivolts for every degree Celsius increase; and that the output voltage for 25 degrees Celsius is 750 mV; and that there is an offset voltage of 400 mV. The offset voltage needs to be subtracted from the analogRead() result, however it is not without vain – having the offset voltage allows the sensor to return readings of below freezing without us having to fool about with negative numbers.

Quick note: A new type of variable. Up until now we have been using int for integers (whole numbers)… but now it is time for real numbers! These are floating point decimals, and in your sketches they are defined as float.

Now we already know how to measure an analogue voltage with our arduino using analogRead(), but we need to convert that figure into a meaningful result. Let’s look at that now…

analogRead() returns a value between 0 and 1023 – which relates to a voltage between 0 and 5V (5000 mV). It is easier on the mind to convert that to a voltage first, then manipulate it into temperature. So, our raw analogRead() result from the TMP36 multiplied by (5000/1024) will return the actual voltage [we're working in millivolts, not volts] from the sensor. Now it’s easy – subtract 400 to remove the offset voltage; then divide it by 10 [remember that the output is 10 mV per degree Celsius]. Bingo! Then we have a result in degrees Celsius.

If you live in the Fahrenheit part of the world, you need to multiply the Celsius value by 1.8 and add 32.

Quick note: You may have seen in earlier sketches that we sent a value to the serial output in order for the arduino software to display it in the serial monitor box. Please note that you cannot use digital pins 0 or 1 if using serial commands. We used Serial.begin(9600); in the void setup(); part of the sketch. You can also send text to the serial monitor, using Serial.print(); and Serial.println();. For example, the following commands:

Serial.print("The temperature is: ");
Serial.print(temperature, 2);
Serial.println(" degrees Celsius");

would create the following line in the serial monitor (assuming the value of temperature is 23.73):

The temperature is 23.73 degrees Celsius

and send a carriage return to start a new line. That is the difference between the Serial.print(); and Serial.println(); commands, the extra -ln creates a carriage return (that is, sends the cursor to the start of the next line. Did you notice the 2 in the Serial.print(); above? You can specify the number of decimal places for float variables; or if you are using an integer, you can specify the base of the number being displayed, such as DEC, HEX, OCT, BIN, BYTE – decimal, hexadecimal, octal, binary, or byte form. If you don’t use the second paramater of Serial.print();, it defaults to decimal numbers for integers, or two decimal places for floating-point variables.

Now let’s read some temperatures! All you need to do is connect the TMP36 up to the arduino board. pin 1 to 5v, pin 2 to analog 0, pin 3 to GND. Here is a shot of the board setup:


And here is the sketch:

/*
example 2.1 - digital thermometer
Created 14/04/2010 ---  By John Boxall --- http://tronixstuff.wordpress.com ---  CC by-sa v3.0
Uses an Analog Devices TMP36 temperature sensor to measure temperature and output values to the serial connection
Pin 1 of TMP36 to Arduino 5V power socket
Pin 2 of TMP36 to Arduino analog 0 socket
Pin 3 of TMP36 to Arduino GND socket
*/
void setup()
{
Serial.begin(9600);   // activate the serial output connection
}
float voltage = 0; // setup some variables
float sensor = 0;
float celsius = 0;
float fahrenheit = 0;
void loop()
{              // let's get measurin'
sensor = analogRead(0);
voltage = (sensor*5000)/1024; // convert raw sensor value to millivolts
voltage = voltage-400;        // remove voltage offset
celsius = voltage/10;         // convert millivolts to Celsius
fahrenheit = ((celsius * 1.8)+32); // convert celsius to fahrenheit
Serial.print("Temperature: ");
Serial.print(celsius,2);
Serial.println(" degrees C");
Serial.print("Temperature: ");
Serial.print(fahrenheit,2);
Serial.println(" degrees F");
Serial.println("_ _ _ _ _ _ _ _ _ _ _ _ _ _  ");
delay (1000); // wait a second, otherwise the serial monitor box will be too difficult to read
}
And there’s nothing like a video, so here it is. The measurements start at room temperature, then an ice cube in a plastic bag is pushed against the TMP36 for a moment, them held between two fingers to warm up again…


Quick note: the while() command. Sometimes you want a sketch to wait for user input, or wait for a sensor to reach a certain state without the sketch moving forward. The solution to this problem is the use of the while() command. It can cause a section of a sketch to loop around until the expression in the while command becomes true.

For example:

while (digitalRead(3) == LOW)
{
Serial.writeln("Button on digital pin 3 has not been pressed");
}

Anyhow, back to the next exercise – it’s now your turn to make something!

Exercise 2.1

Recently the cost of energy has spiralled, and we need to be more frugal with our heating and cooling devices. Unfortunately some members of the family like to use the air conditioner or central heating when it is not really necessary; many arguments are caused by the need for the heating/cooling to be on or off. So we need an adjudicator that can sit on the lounge room shelf and tell us whether it’s ok to use the heating or cooling.

So, create a device  that tells us when it is ok to use the air conditioner, heater, or everything is fine. Perhaps three LEDs, or a single RGB LED. Red for turn on the heat, blue for turn on the air conditioner, and green or white for “You’re fine, you don’t need anything on”. You will need to define your own temperature levels. Living here in north-east Australia, I’m going to have the air conditioner on above 28 degrees C; and the heat can come on at 15 degrees C.

Hopefully you are thinking about the voltmeter we made in chapter one, that should give you a starting point. If not, go back now and have a look. Otherwise, hop to it…
Anyway, here is my board layout…
You will need:
  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Either three LEDs or an RGB LED
  • 3 x 560 ohm 0.25 W resistors. They are to reduce the current to protect the LEDs.
  • a breadboard and some connecting wire
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • a camera (optional) – to document your success!
And a sketch to solve the exercise: (download)
/*
exercise 2.1 - Climate Control Judge
Created 14/04/2010 ---  By John Boxall --- http://tronixstuff.wordpress.com ---  CC by-sa v3.0 Share the love!
Measures temperature with Analog Devices TMP36 and compares against minimum temperature to use a heater or air conditioner
*/
int redLED = 13; // define which colour LED is in which digital output
int greenLED = 12;
int blueLED = 11;
float voltage = 0; // set up some variables for temperature work
float sensor = 0;
float celsius = 0;
float heaterOn = 15; // it's ok to turn on the heater if the temperature is below this value
float airconOn = 26; // it's ok to turn on the air conditioner if the temperature is above this value
void setup()
{
pinMode(redLED, OUTPUT);    // set the digital pins for LEDs to outputs
pinMode(greenLED, OUTPUT);  // not necessary for analogue input pin
pinMode(blueLED, OUTPUT);
}
void loop()
{
digitalWrite(redLED, LOW);    // switch off the LEDs
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, LOW);
// read the temperature sensor and convert the result to degrees Celsius
sensor = analogRead(0);       // TMP36 sensor output pin is connected to Arduino analogue pin 0
voltage = (sensor*5000)/1024; // convert raw sensor value to millivolts
voltage = voltage-400;        // remove voltage offset
celsius = voltage/10;         // convert millivolts to Celsius
// now decide if it is too hot or cold.
if (celsius>=airconOn)
{
digitalWrite(blueLED, HIGH); // ok to turn on the air conditioner
} else if (celsius<=heaterOn)
{
digitalWrite(redLED, HIGH);
} else
{
digitalWrite(greenLED, HIGH); // everything normal
}
delay(1000); // necessary to hold reading, otherwise the sketch runs too quickly and doesn't give the LEDs enough time to
                 // power up before shutting them down again
}
And of course a video. For demonstration purposes, I have altered the values by making them very close, so it’s easier to show you the LEDs changing. The plastic bag used in the video is full of ice water.

Well that was interesting, I hope you enjoyed it and have some ideas on how to put temperature sensors to use. But now it is time to look at a library or two…
Quick note: As you know, there are several commands in the processing language to control your arduino and its thoughts. However, as time  goes on, people can write more commands and make them available for other arduino users. They do this by creating the software that allows the actual Atmel microcontroller interpret the author’s new commands. And these commands are contained in libraries. Furthermore, as Arduino is open-source, you can write your own libraries and publish them for the world (or keep ‘em to yourself…) In the arduino IDE software, have a look at the Sketch>>Import Library… menu option. Also, check out here for more libraries! Now to put one to good use…

Update – LCDs were orginally explaned at this point, however they are now explained in their own article – chapter 24. Don’t forget to return to try out the examples and the rest of this chapter!

Exercise 2.2

This is our most complex project to date, but don’t let that put you off. You have learned and practised all the commands and hardware required for this exercise. You only need a little imagination and some time. Your task is to build a digital thermometer, with LCD readout. As well as displaying the current temperature, it can also remember and display on request the  minimum and maximum temperatures – all of which can be reset. Furthermore, the thermometer works in degrees C or F.

First of all, don’t worry about your hardware or sketch. Have a think about the flow of the operation, that is, what do you want it to do? For a start, it needs to constantly read the temperature from our TMP36 sensor. You can do that. Each reading will need to be compared against a minimum and maximum value. That’s just some decision-making and basic maths. You can do that. The user will need to press some buttons to display and reset stored data. You can do that – it’s just taking action if a digital input is high. I will leave the rest up to you.

So off you go!

You will need (this may vary depending on your design, but this is what we used):

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Water (you need to stay hydrated)
  • 2 x 10k 0.25 W resistors. They work with the buttons to the arduino
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • 2 little push buttons
  • breadboard and some connecting wire
  • 16×2 character LCD module and a 10k linear potentiometer or trimpot (For LCD contrast)
  • Analog Devices TMP36 temperature sensor (element-14 part number 143-8760)
  • a camera (optional) – to document your success!

For inspiration, here is a photo of my board layout:




and a video clip of the digital thermometer in action.

And here is the sketch for my example – Exercise 2.2 sketch example. I hope you had fun, and learned something. Now it’s time for Chapter Three.

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

April 15, 2010 Posted by | arduino, LCD, microcontrollers, tutorial | , , , , , , , , , , , , , | 37 Comments

Part review – Linear Technology LT1302 DC/DC step-up converter

In today’s part review, we have a look at the Linear Technology LT1302. This is a fascinating part as it can increase a supply voltage and still maintain a reasonable current. For example, with a supply voltage of 2 volts the LT1302 can give you 5V at 600 mA or 12V at 150 mA. That’s pretty awesome, and can save you a lot of space when designing products, such as reducing the number of cells required in a battery pack. One example of such a product is the very popular mintyboost battery pack booster by ladyada.

But first as usual, let’s say hello…

There are two versions of this part, the LT1302 which allows a variable output; and the LT1302-5, with a fixed output voltage of 5.05V to 4.97V in high current mode.

How does it seem to make something out of nothing? With a few external components that are used to store electrical charge, and some internal oscillators. The chip can be sensitive to noisy input supply voltages, so there is a need for the capacitor C1 to be very close to the LT1302. Also, the diode must be a 2A schottky and not a regular one like a 1N4001, as they cannot react fast enough to the switching of the LT1302. The purpose of the oscillations is to allow the inductor to fill with current, and on the alternate oscillation cycle, it releases that current into a capacitor via the diode, and the voltage of this current is higher than the supply voltage. This is a very basic explanation, and more details can be found in the data sheet (link below).

But as always, it’s more interesting to do something than read about it – so we’ve constructed the demonstration circuit from the data sheet (below).

And here it is:

demo circuit ready to go

With an input supply voltage of 2 x 1.5V AA alkaline cells, our output voltage is 5.06V. This should be good for 600mA.

Finally, here is the very interesting and detailed data sheet: LT1302 data sheet.

So there you have it! Another simple, useful and easy to implement part for you to use in your projects.

Thank you to Linear Technology for the samples of the LT1302 integrated circuits. They will also be used in a forthcoming project and an open-source kit.

Once again,  thank you for reading. Please leave feedback and constructive criticism or comments at your leisure… and to keep track, subscribe using the services at the top right of this page!

April 13, 2010 Posted by | part review | , , , , , , , , , , , , , , | 11 Comments

Education – Soldering is Easy!

Soldering to some people can seem scary and dangerous. And if done incorrectly, or in the wrong state of mind, and/or with the wrong equipment – it can be. A fine person by the name of Andie Nordgren has come up with a comic flyer that explains soldering in a very easy to understand method. Andie has been a champ and placed it into the public domain, so please print it out, email it, and generally distribute it far and wide. More about the comic and Andie at their blog here. I have also placed the files below for you to download directly.

Have fun!

And here is the pdf version of the comic.

Personally I highly recommend the use of a third hand, as detailed in my kit reviews. Furthermore, the use of a fume extractor… just blowing away the fumes isn’t such a good idea. A good extractor isn’t that expensive, a little noisy, but definitely worthwile:

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.

April 13, 2010 Posted by | education, learning electronics | , , , , , , , , , | 5 Comments

Part Review – Intersil ICL7660

Hello readers

Today we are going to quickly examine a very simple yet useful part – the Intersil ICL7660 CMOS voltage converter. Huh? This is the part you have been looking for when you needed -5V and you’re not running off a multi-tap transformer. For example, some old-school TTL electronics projects need +/-5VDC power rails. Or if you are using the ICL7107 analogue to digital/3.5-digit display driver IC (as used in my bbboost project).

But first of all, let’s say hello:

To do so with the ICl7660 is very simple, you only need two 10uF electrolytic capacitors! Honestly, I couldn’t believe my luck when I discovered this part, that is why I am writing about it today.

Firstly, how does it work? A very simple definition would be: the 7660 charges one capacitor, then the other – an oscillator controls the charging cycles between C1 and C2 and inverts the polarity, allowing the capacitors to discharge at an inverted voltage (negative instead of positive). For a more detailed explanation, have a loot at the data sheet. Furthermore, if the oscillation frequency interferes with other parts of your circuit, you can boost the oscillation rate with the use of a NAND gate, from an external logic IC (4011, etc.)

However due to the oscillations, there is a ripple in the supplied -5V. I only wish I had an oscilloscope to show you this, perhaps next month. In the meanwhile, there is an explanation of this in the data sheet.

At this stage, let’s have a quick look at an example circuit, from the data sheet – figure 13A.

And here it is in real life. The circuit on the breadboard to the left is my simple 12VAC > 5VDC converter. I am not that well off at the moment, so it will have to do.

So there you have it  - a very easy and cheap way to get yourself -5 volts DC.

Some information from this review obtained from Intersil website and the ICL7660 data sheet; these parts purchased by myself without knowledge of manufacturers or retailers.

Once again,  thank you for reading. Please leave feedback and constructive criticism or comments at your leisure… and to keep track, subscribe using the services at the top right of this page!

April 12, 2010 Posted by | part review | , , , , , , , , , , , | 2 Comments

Follow

Get every new post delivered to your Inbox.

Join 3,838 other followers

%d bloggers like this: