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

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

relayinternalssmall

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:

examp3p1

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

Our hardware is exactly as the schematic above. Here is a photo:

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

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:

So to blink that LED 42 times, execute blinkblink(42); Want to specify your own delay? Try this:

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:

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:

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)

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:

example3_2small

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

servosmall

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:

protractorsmall

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:

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

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

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

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:

The board layout is quite simple, just the three servo wires to the Arduino board:

example3_3small

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:

exer3_1boardsmall

exer3_1board2small22

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.

LEDborder

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

The following two tabs change content below.

John Boxall

Founder, owner and managing editor of tronixstuff.com.

8 Responses to “Getting Started with Arduino! – Chapter Three”

  1. Mark says:

    Hi. I have spent a few hours looking at your site. Learned a lot. So far every sketch has worked exactly as planned.

    more to see. Thank you very much for the information

  2. Rich says:

    Great help. One question. I see the +12V from the power supply but do not see any ground wire from the power supply? Is it connected to the ground from Arduino?? Is it not used??? Thanks

  3. Mark Stevens, Sr. says:

    Hi John, I am new to Arduino and I find your series very helpful. All previous sketches have been working fine but I cannot get example 3.1 to work. The compiler error says:
    Example_3_1.ino: In function ‘void loop()':
    Example_3_1:10: error: ‘lt’ was not declared in this scope
    Example_3_1:10: error: expected primary-expression before ‘=’ token
    error: expected ‘)’ before ‘;’ token
    error: name lookup of ‘i’ changed for new ISO ‘for’ scoping
    error: using obsolete binding at ‘i’
    error: expected ‘;’ before ‘)’ token
    I feel part of the problem is in the loop ‘for’ statement/algorithm where i<=20;
    I am running this sketch on Arduino 1.0.5

    Any enlightenment would be appreciated.

    Thanks,

    Mark Stevens
    [email protected]

  4. BG says:

    Hey, I got the analog thermometer working!
    Didn’t work at first, one of the servos was defective.
    After I replaced the project worked just like the video.

  5. Quang says:

    Very helpful educational materials. There are a lot tutorials on internets. But this one site gives the most easy-to-understand tutorials. Teachers are not good if they don’t know how to convey in simple terms.
    Thanks.

Trackbacks/Pingbacks


Leave a Reply

Receive notifications of new posts by email.

The Arduino Book

Arduino Workshop

Für unsere deutschen Freunde

Dla naszych polskich przyjaciół ...

Australian Electronics!

Buy and support Silicon Chip - Australia's only Electronics Magazine.

Use of our content…

%d bloggers like this: