Tag Archive | "arduino tutorial"

Moving Forward with Arduino – Chapter 14 – XBee introduction

Learn how to use XBee wireless data transceivers with Arduino. This is part of a series originally titled “Getting Started with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.

Updated 02/03/2013

We will examine the Series 1 XBee wireless data transceivers from Digi in the USA. Although in the past we have experimented with the inexpensive 315MHz transmit/receive pair modules (chapter 11), they have been somewhat low in range and slow with data transmission. The XBee system changes this for the better.

First of all, what is an Xbee module? It is a very small piece of hardware that can connect wirelessly with another using the Zigbee communication protocols. There are many different models, including aerial types and power outputs. In this tutorial we’re using Series One XBees.

From Wikipedia, Zigbee is:

ZigBee is a specification for a suite of high level communication protocols using small, low-power digital radios based on the IEEE 802.15.4-2003 standard for wireless home area networks (WHANs), such as wireless light switches with lamps, electrical meters with in-home-displays, consumer electronics equipment via short-range radio. The technology defined by the ZigBee specification is intended to be simpler and less expensive than other WPANs, such as Bluetooth. ZigBee is targeted at radio-frequency (RF) applications that require a low data rate, long battery life, and secure networking.

Phew. For this chapter I will try and keep things as simple as possible to start off with. Here is an image of a typical Xbee unit:

Note that the pin spacing is small than 2.54mm, so you cannot just drop these into a breadboard. However for the purposes of our experimenting more equipment is needed. Therefore I am making use of this retail package from Sparkfun:

xbeeretailpackopenedsmall

This bundle includes two Xbee modules, an Xbee shield to connect one of the modules to an Arduino Uno-style board. When it comes time to solder the sockets into your shield, the best way is to insert them into another shield that is upside down, then drop the new shield on top and solder. For example:

solder2s

Finally, the bundle also includes a USB Explorer board, which allows us to connect one Xbee to a personal computer. This allows us to display serial data received by the Xbee using terminal software on the PC. One can also adjust certain Xbee hardware parameters by using the explorer board such software.

Let’s do that now. You will need some terminal software loaded on your computer. For example, Hyperterminal or Realterm. Plug an Xbee into the explorer board, and that into your PC via a USB cable. Determine which port (for example COM2:) it is using with your operating system, then create a new terminal connection. Set he connection to 9600 speed, 8 bits, no parity, 1 stop bit and hardware flow control. For example, in Hyperterminal this would look like:

Once you have established the connection, press “+++” (that is, plus three times, don’t press enter) and wait. The terminal screen should display “OK”. This means you are in the XBee configuration mode, where we can check the settings and change some parameters of the module. Enter “ATID” and press enter. The terminal window should display a four-digit number, which is the network ID of the module. It should be set by default to 3332. Unless you plan on creating a huge mesh network anytime soon, leave it be. To be sure your modules will talk to each other, repeat this process with your other XBee and make sure it also returns 3332. However as this is the default value, they should be fine.

Now for our first example of data transmission, insert one Xbee into the explorer module, and the other into the Xbee shield. With regards to the Xbee shield – whenever it is connected to an Arduino board and you about to upload a sketch, look for a tiny switch and change it to DLINE from UART. Don’t forget to change it back after uploading the sketch. See:

shieldswitchss

We are going to use the two Xbee modules as a straight, one-way serial line. That is, send some data out of the TX pin on the transmit board, and receive it into the terminal on the PC. Now upload this sketch into your Arduino board. This is a simple sketch, it just sends numbers out via the serial output. Then set the switch on the shield back to UART, and reset the board. If you can, run this board on external power and put it away from the desk, to give you the feeling that this is working 🙂

Note: More often that not one can purchase AC plug packs that have USB sockets in them, for charging fruity music players, and so on.

acusbss

Or you might have received one as a mobile phone charger. These are great for powering Arduino boards without using a PC. Now ensure your explorer module is plugged in, and use the terminal software to connect to the port the explorer is plugged into. After connecting, you should be presented with a scrolling list of numbers from 0 to 99, as per example 14.1 sketch:

numbers

How did you go? Sometimes I used to get the COM: ports mixed up on the PC, so that is something to keep track of. If you are powering both Xbees from your PC using USB cables, double-check the terminal software is looking at the explorer board, as an Arduino transmitting serial data through an Xbee shield will still send the same data back to the PC via USB.

Now that we have sent data in one direction, we can start to harness the true power of Xbees – they are transceivers, i.e. send and receive data. Next, we’ll create an on-demand temperature and light-level sensor. Our arduino board will have a temperature sensor and a light-dependent resistor, and using the terminal on the computer, we can request a temperature or light-level reading from the remote board. More about temperature sensors in chapter two. First of all, the remote board hardware setup:

exam14p2boardss

… and the schematic:

exam14p2schemss

 

It never hurts to elevate your other Xbee:

xbeewallss

For the PC side of things, use the explorer board and USB cable. Here is the sketch. It is quite simple. The remote board ‘listens’ to its serial in line. If it receives a “1”, it reads the temperature, converts it to Celsius and Fahrenheit, and writes the result to its serial out line, which is sent over our Xbee data bridge and received by the host computer. A “2” will result in the analogue value of the photocell to be sent back as a “light level”. Once again we use the terminal software to control the system.  Here is a quick video of the terminal in action:

The speed is quite good, almost instantaneous. By now hopefully you can see how easy it is to end some data backwards and forwards over the ether. The range is only limited by the obstacles between the Xbee transceivers and the particular power output of each model. With example 14.2, there were two double-brick walls between them. Furthermore, we can build fully computer-independent systems that can talk to each other, such as more portable remote controls, or other data-gathering systems. In the next few chapters, sooner rather than later.

LEDborder

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

Posted in arduino, learning electronics, lesson, microcontrollers, RTL-11445, tutorial, wireless, WRL-09819, WRL-11215, xbeeComments (9)

Blinky the one-eyed clock

In this tutorial you learn how to make a blinking clock with a difference!

Updated 18/03/2013

Followers of my website would realise that I tend to make too many clocks in those tutorials. Well, I like making clocks… so here is another one. However this time I have tried to make the most simple version possible. Usually projects will have many LEDs, or perhaps an LCD, buzzers, buttons, all sorts of things. Which looks great and will impress many. But the other day I thought to myself … “how few things do you need to show the time?”

So here is my answer to that question: Blinky the one-eyed clock …

workingsss

It reminds me of the giant killer orb from The Prisoner… Using a minimal Arduino bootloader system, a DS1307 real time clock IC and an RGB diffused LED … we can make a clock that blinks the time, using the colours of the LED to note different numerical values. For example, if the time is 12:45, the clock will blink red 12 times, then show blue for a second (think of this as the colon on a digital clock) then blink four times in green (for forty minutes), then blink three times in red for the individual minutes. If there is a zero, blink blue quickly. Then the clock will not display anything for around forty seconds, then repeat the process. Here he (she, it?) is blinking the time:

Setting the clock is simple. It is set to start at 12:00 upon power up. So for the first use you have to wait until about five seconds before midday or midnight, then power it up. To save cost it doesn’t use a backup lithium battery on the real-time clock IC, but you could if you really wanted to. If you would like to follow my design process narrative, please read on. If you only want the sketch and schematic, 🙁 head to the bottom of this article.

Design process narrative…

So let’s get started!

The first thing to do was test the RGB LED for brightness levels, so I just connected it to the digital output pins of my Eleven via suitable current-limiting resistors. Each LED is going to be different, so to ensure maximum brightness without causing any damage you need to calculate the appropriate resistor values. This is quite easy, the formula is: resistor (ohms) = voltage drop / LED current So if you have a 5 V supply, and LED that needs only 2 volts, and draws 20 milliamps (0.2 amps) , the calculation will be: resistor = (5-2)/0.02 = 150 ohms. To be safe I used a 180 ohm resistor. The LED was tested with this simple sketch:

It was interesting to alter the value of d, the delay variable, to get an idea for an appropriate blinking speed. Originally the plan was to have the LED in a photo frame, but it was decided to mount a ping-pong ball over the LED for a retro-style look.  Here is a short video of the result of the test:

If you are going to use a ping-pong ball, please be careful when cutting into it with a knife, initially it may require a lot of force, but once the knife cuts through it does so very quickly:

cuttingppballss

Now it was time to develop the sketch to convert time into blinks. The sketch itself is quite simple. Read the hours and minutes from the DS1307 timer IC; convert the hours to 12 hour time; then blink an LED for the number of hours, display another colour for the colon; divide the minutes by ten and blink that in another colour; then the modulus of minutes and ten to find the individual minutes, and blink those out. Here is the first sketch I came up with. Finally, the code was tested using the Eleven board and my DS1307 real time clock shield. It is best to use existing hardware while testing, before committing to purchasing new hardware and so on. So here it is on the breadboard:

workingprototype1ss

And telling the time! In this example, the time is 3:45…

But perhaps that was a little bland. By using analogWrite() we can control the brightness of the LED segments. So now there are two more functions, whiteGlow() and blueGlow(); whose purpose is to make the display “glow” by increasing then decreasing the brightness. And scale back the amount of blinking, to increase battery life and make blinky less obvious. So now the display will glow white to announce the forthcoming display of time, wait a second, blink the time (with a blue glowing colon) then stay dark for ten seconds before repeating the process. Here is a quick demonstration of this display style:

Here is the sketch for the above demonstration, and the final one I will use with the hardware prototype. Once happy with the sketch, I put a fresh ATmega328 with Arduino bootloader in the board and programmed it with the blinky sketch, to be used in the final product.

Next was to build my own hardware. My last hardware unknown is the amount of current the circuit draws. Once I know this the correct voltage regulator and power supply can be decided upon. I had a fair idea it would be less than 100 milliamps, so I put a 6V battery onto supply duty via a 78L05 5V regulator (data sheet), and recorded the result:

So it varies, between 20.5 and 46 mA. As it only reaches 46 mA for a short time, we could consider the constant draw to be averaged out at 30 mA. I really want this to be able to run from a battery, but without having an external lead-acid battery lurking around, it will need a plug-pack with an output voltage greater than 7V DC. Another alternative would be to run it from a USB socket, a nice source of 5V. If doing so, there wouldn’t be a need for the 78L05 regulator. Which brings us to the  circuit diagram, which includes the power regulator:

blinkyschematicss

 

It does not allow for programming in the circuit, so you will need to program the microcontroller on another Arduino or compatible board, then transfer it to the blinky circuit board as described above. At this stage I tested it again, but using a solderless breadboard. In doing so you can make final hardware checks, and  generally make sure everything works as it should. This is also a good stage to double-check you are happy with the display behaviour, default time and so on.

breadboardedss

Time to solder up the circuit on some stripboard. Blank stripboard varies, but luckily I found this and a nice box to hold it in:

boxandpcbss

Stripboard does vary between retailers and so on, so you will need to work out the layout with your own board. In doing so, please double-check your work – follow the layout against the schematic and so on. Have a break, then check it again. There is nothing worse than soldering away to realise you are one strip too far over or something. My hand-eye coordination is not the best, therefore my soldering isn’t pretty, but it works:

solderedfrontss

 

solderedrearss

One would say that there is a good argument for making your own PCBs… and I would start to agree with that. The LED is soldered to some short leads to give it a bit of play, and some heatshrink over the legs to keep them isolated:

heatshrinkledss

 

And finally, to add a DC socket to feed blinky some power…

finalbaress

 

The last thing was to check the soldering once more under natural light, to check for bridges or shorts, then have a cup of tea. Upon my return I drilled out a hole in the enclosure lid for the LED, and one one the side for the DC socket, and fitted the lot together… and success! It worked 🙂

So there you have it. The journey from a daydream to a finished product… well a prototype anyway. But it works, and that is the best feeling of all. You can download the schematic from here. And here is the Arduino sketch:

I hope you enjoyed reading this post and hopefully felt inspired enough to make your own.

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

Posted in arduino, clocks, ds1307, microcontrollers, projects, RGB LED, tutorialComments (18)

Getting Started with Arduino – Chapter Thirteen

This is part of a series titled “Getting Started with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.

Welcome back fellow arduidans!

This chapter we will examine piezo buzzers, continue with our alarm clock, and then spend more time with the wireless radio modules by creating some remote control systems and sending various data over the airwaves. So let’s go!

Sometimes you would like to make some noise. For warnings, fun, or to annoy people. A very simple and inexpensive way to do this is with a piezoelectric buzzer. In simple terms, it contains a disc of metal that can deform when a current is applied to it. If you apply an alternating current at a high enough frequency, the disc will move fast enough to create a sound wave, something we can hear.

This is an example of a small piezo buzzer:

tdk_ps1240ss

This example was very cheap, less than $2.  Here is the data sheet: PS1240.pdf. It can run from between 3 and 30 volts AC – which thankfully the output from our Arduino falls between. But how do you output AC from an Arduino? There are several ways, however the easiest is using pulse-width modulation (PWM). If you look at your Arduino’s digital output sockets, some are labelled PWM. Using the function analogWrite(); you can send a PWM signal to the buzzer. For example:

The sketch above will beep the piezo on and off, and be somewhat annoying. Perfect. However with the analogWrite(); function it is impossible to use the full frequency range of the piezo buzzer. With a value of 254 for the duty cycle, the frequency generated is around 1500 Hz:

ps1240_analogwrite254ss

Later on we will explore ways to create a better range of sounds. But now to use that buzzer in our alarm clock to help wake people up.

Continuing on from exercise 12.1, this chapter we will add some more features to the clock. First of all is the piezo buzzer. As we just discussed above, using it is quite simple. On the hardware side of things, we can replace the resistor and LED connected between digital pin 6 and ground with our piezo buzzer. On the software side of things, instead of digitalWrite(6, HIGH); we use analogWrite(6,128);. Very easy. And here is a short video – with sound!

Moving on, it’s time to clean up the alarm function in general. Most alarm clocks have a snooze function, so let’s add one as well. When the alarm sounds, the user presses button four to turn off the buzzer, and is then asked if they want to snooze. Button one is yes and four is no. If yes, add ten minutes to the alarm time and carry on as normal. When adding the ten minutes be sure to check for increasing the hour as well, and also take into account the jump from 2359h to 0000h (or 2400h). If the user presses no, the alarm is switched off and the user warned with the flashing “OFF”.

Example 13.1Here is a demonstration of what I came up with:

The hardware is the same as exercise 12.1, except the LED and resistor from digital pin 6 to GND has been replaced by the piezo buzzer as described earlier. You will find the snooze function is controlled in the checkalarm(); function in the sketch.

 

In chapter eleven we started to examine the inexpensive serial data transmitter/receiver pairs. In this chapter we will continue working with them, to create the backbone of various remote control and data transmission ideas for you to use. For our next example, consider a simple remote control with four channels. That is, it has four buttons, and the transmitter will send out the state of the four buttons, high or low.

This would be useful for a remote control toy or a perhaps robot. The sketches are quite simple. The transmitter reads the buttons with digitalRead(); then transmits a single letter a~h – which is code for a button and its state. For example, a means button 1 is low, h means button 4 is high. The receiver just decodes that a~h code and sends the result to the serial monitor window. Here is the sketch for the transmitter and receiver.

To save time I will use the button board created in example 12.3. Here are the schematics for the transmitter and receiver sections:

example13p2schemss

And set up:

example13p2ss

And finally a video of the serial monitor showing the button states:

Now that we have the data being sent across, let’s get some switching happening. Using the same transmitter system as example 13.2, we will turn on or off four LEDs at the receiving end. Of course you could use relays, transistors, 74HC4066s, etc instead. Our sketch decodes the transmitted data once more, but sets the digital pins high or low depending on the received code. Here is the schematic for the new receiver:

example13p2schemss

… and the board laid out:

example13p3boardss

And again a quick demonstration video:

Now that you can turn the LEDs on or off with a push of a button, there are a few other ways of controlling those digital outputs with the remote control rig without altering the hardware.

For out next example, we will control two digital outputs with the four buttons, as each output will have an on and off button. Consider this sketch; and the following demonstration video:

So there you have various ways to control digital outputs and send basic data across a wireless radio serial data link.

LEDborder

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

Posted in 315 MHz, 433 MHz, arduino, education, learning electronics, lesson, microcontrollers, piezo, tutorial, wirelessComments (12)

Review – Texas Instruments TLC5940 16-channel LED driver IC

Hello readers

Today we are going to examine the Texas Instruments TLC5940 16-channel LED driver IC. My reason for doing this is to demonstrate another, easier way of driving many LEDs as well as LED display modules that are common-anode. If you have a common-cathode display module, you should have a look at the Maxim MAX7219. Moving along, here is the IC:

tlc5940sss

Another nice big DIP IC. Also available in HTSSOP and QFN packaging. What can this IC do for us? It can control 16 LEDs per IC, and also be cascaded to control more and more, with the display data arriving via a serial line in the same manner as a 74HC595 shift register. Furthermore, another benefit of this IC is that you don’t need matching current-limiting resistors for your LEDs, as this IC is a current sink, in that the current flows from the 5V rail, through the LED, then into the IC. However, it can control the brightness of the LEDs using pulse-width modulation over 4096 steps via software, or using a single resistor.

What is pulse-width modulation? Normally an LED might be on, or off. But if you switch it on and off very quickly, it does not look as bright (as it is not on 100% of the time). If you alter the period of time between on and off, you can alter the perceived brightness of the LED. Here is an example, compare the brightness of the LED bars against the display of the CRO – as the brightness increases, the voltage (amplitude [vertical thickness]) spreads across the entire time period (horizontal axis); as the brightness decreases, the voltage spread across time retreats:

Using the IC is very easy on the hardware front. Here is the data sheet: TLC5940.pdf. The pinout diagram is quite self-explanatory:

Pins OUT0~OUT15 are the current-sink pins for each LED. When one is selected they allow current to flow into the IC from the 5V rail, with the LED in between – turning it on. However it is easier to understand with a practical example, such as this:

tlc5940demo1schematic

If you are using an Arduino Mega-style board, the wiring is a little different, please see here for the instructions.

Here we have our Arduino board or compatible sending serial data to the TLC5940 to control sixteen LEDs. The 2k ohm resistor is required to set the maximum current available to flow through the LEDs, thereby adjusting their brightness. Using software you can adjust the brightness with PWM for each LED by itself. Very important: this circuit will need external power into the Arduino or a separate 5V power supply. The circuitry on the breadboard draws up to ~318 mA by itself – running the Arduino from USB only made it somewhat flaky in operation. Here is the circuit in action with an ammeter between the breadboard and 5V out on the Arduino:

Anyhow, let’s get moving once more – here is the assembled demonstration circuit:

tlc5940demo1bbs

For our example, we will be using the Arduino way of doing things. Thankfully (once more) there is a library to make controlling the IC exponentially easier. The library page and download files are available from here.  If you need guidance on installing a library, please visit here. However the commands to control the IC are quite simple with the Arduino library.

First of all, include the TLC5940 library, as such:

Then in void setup(); you create the object using the function:

You can insert a number between 0 and 4095 to set the starting PWM (LED brightness) value, however this is optional. Setting an output for display requires two functions, first Tlc.set(l, p); where l is the output (0~15) and p is the PWM brightness level – then execute Tlc.update(); which sends the command to the IC to be executed. The sketch below is easy to follow and understand the process involved.

Moving forward with the demonstration, here is the sketch  – TLC5940demo.pdf, and the video clip of operation:

When the LEDs are glowing from dim to bright and return, we are altering the PWM value of the LEDs to adjust their brightness. This also occurs during the last operation where the LEDs are operating like the bonnet of KITT.

Below is an example of TLC5940 use by JM – he has made an awesome RGB LED cube:

Well once again that’s enough blinkiness for now, again this is another useful IC that helps simplify things and be creative. As always, avoid the risk of counterfeit ICs  – so please avoid disappointment, support your local teams and buy from a reputable distributor. Living in Australia, mine came from element-14 (part number 1226306). So have fun! High resolution photos are available from flickr.

Remember, if you have any questions at all please leave a comment (below). We also have a Google Group dedicated to the projects and related items on the website – please sign up, it’s free and we can all learn something.

Posted in arduino, lesson, part review, tlc5940, tutorialComments (28)

Part review – NXP 74HC238 Decoder/demultiplexer

Hello readers

Today we are going to examine the 74HC238 decoder/demultiplexer IC. My reason for writing this was to examine another way to get more output pins when using an Arduino or compatible board. However you can use any combination of three logic lines to turn on or off eight mutually exclusive outputs. How? Let’s find out…

First of all, here is the IC:

74hc238imagesm

It is also available in SO16, SSOP16,  TSSOP16 and DHVQFN16 packages. What? Here is a good list of various SMD packaging types. The pin layout is very simple, apart from +5V and ground, you have six pins that control the outputs, and eight output pins, however in reality you only need to control three from the microcontroller or other logic lines. Here is the pinout diagram:

To get the output pins high, you use a combination of levels on 74HC238 pins A0~A2 and possibly E3. If you leave E3 low, no outputs can be set to high. The input combination required for each output is described in this table from the data sheet:

functiontable

Notice that columns with an X can be set either high or low, but you must not leave them floating, so always connect or set an X to high or low. If you need to have active low outputs (that is, outputs are high instead of low), there is the 74HC138. So now to do this in real life! Here is a demonstration schematic to use the 74HC238 with an Arduino Uno or 100% compatible board:

democircuit

… and in real life:

bbs

And here is a demonstration video, using the following sketch:

As with most other ICs of this type, you can only source 25 milliamps of current from each output, so if you need more you will have to consider the use of a switching NPN transistor etc. Although only one output can be high at a time, if you scan them quick enough, you can create the illusion that all are on at once (as in the video). Apart from LEDs and other items, you could use this IC to control stepper motors or even create a safe working environment on a model train layout.

To conclude, the 74HC238 offers one of several ways to control more things with less control pins. Ideal for mutually exclusive outputs, however if you needed more than one high at once, the 74HC595 shift register would be the better solution. (See here for a 74HC595 tutorial).

You can get the 74HC238 from our store – tronixlabs.com – offering a growing range and Australia’s best value for supported hobbyist electronics from adafruit, DFRobot, Freetronics, Seeed Studio and much much more.

visit tronixlabs.com

As always, 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

Posted in 74HC238, arduino, lesson, part review, tronixlabs, tutorialComments (2)

Getting Started with Arduino – Chapter Twelve

This is part of a series titled “Getting Started with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.

Welcome back

This chapter we will spend some more time with the rotary encoder by using it to control a clock, look at ways of driving a common-anode LED display with Arduino, and make a usable alarm clock with which we can start to move from the prototype stage to an actual finished product – something you would be proud to give to someone.

So off we go…

In chapter eleven, we looked at getting some values from the rotary encoder. Not the easiest way of receiving user input, but certainly interesting. This week I have an example for you where the encoder is used for setting the time of a digital clock. This example is basically two previous projects mashed together. It consists of the LED digital clock from exercise 7.1, and the rotary encoder sketch from example 11.2. The sketch was quite simple in theory, but somewhat complex in execution. The idea was to read the decoder, and after every read, display the time. However, if the encoder’s button was pressed, the time set function would be activated. At this point, you turn the encoder in one direction to set the hours, and the other direction to set the minutes. Then press the button again to set that time and return to normal operations.

To recreate it you will need:

  • Your standard Arduino setup (computer, cable, Uno or 100% compatible)
  • Seven 560 ohm 1/4 watt resistors
  • Four 1 kilo ohm 1/4 resistors
  • Four BC548 NPN transistors (if you cannot find these, you can use 2N3904)
  • Two 74HC595 shift registers
  • DS1307 timer IC circuit components (see this schematic from chapter seven) or a pre-built module
  • Solderless breadboard and connecting wires

Here is the sketch for your perusal, and the matching schematic (sorry, I forgot to add the DS1307 module – see example 12.2 schematic below for how to do this):

example12p1small

… in real life:

example12p1boardsmall

and a video clip:

After watching that clip you can soon see that there is an issue with the encoder. As a normal switch can bounce (turn on and off very very quickly in the latter part of operation), so can a rotary encoder. That is why it would sometimes return a result of clockwise, instead of anti-clockwise. Furthermore, they are right little pains when trying to use in a breadboard, so if you were going to use one in greater lengths, it would pay to make up your own little breakout board for it. Therefore at this stage we will leave the encoder for a while.

You may also have noticed the extra shield between the real time clock shield (yellow) and the arduino board. It is the Screwshield for Arduino – reviewed here. It is very useful to making a stronger connection to the I/O pins, or using normal multi-core wires.

pinsborder

Next on the agenda is the common-anode LED display. Normally the LED display we have demonstrated in the past has been common-cathode, and very easy to use. Current would flow from the power supply, through the shift register’s outputs (for example the 74HC595), through current-limiting resistors, into the LED segment, then off to earth via the cathode. Current flows through a diode from the anode to the cathode, and finally back to earth/ground. For a refresher on diodes, please read this article. The other month I found this style of useful LED display:

clockdisplaysmall

Absolutely perfect for our clock experimentations. A nice colon in the middle, and another LED between the third and fourth digit which could make a good indicator of some sort. However the one catch (always a catch…) is that is was common-anode. This means that current starts from the power supply, through the common anode pin for the particular digit, then the LED segment, the LED’s individual cathode pin, through the current-limiting resistor and then to ground. With the current flowing in the opposite direction via a common anode, we can’t just hook the display up to our 74HC595 shift register.

Therefore, we will need the shift register to control switches to allow the current to flow through each segment, just like we have done previously controlling the cathodes of a common cathode display (see example 12.1). So to control the digits of this new display, we will need twelve switches (eight for the segments of the digit, and four to control the anodes). That would mean twelve BC548  transistors and 10k ohm resistors, and a lot of mess.

Instead we will now use the 74HC4066 quad bilateral switch IC. I have reviewed this chip being used with Arduinos in a separate article here. The 74HC4066 is quite a common chip, available from many suppliers including: element14/Newark (part number 380957), Digikey (part number 568-1463-5-ND) or Mouser (771-74HC4066N). If you cannot find them, email me and I can sell you some at cost plus postage. Once you have a understanding of this IC, please consider the following circuit:

example12p2schematic

Most of this should be easily understood. One shift register is controlling the anodes, turning them on and off via a 74HC4066. In past examples this shift register would have turned off common cathodes via a 10k resistor and an NPN transistor. The other shift register is controlling the individual LEDs for each digit via a pair of 74HC4066s (as they only have four switches per IC).

Here is the sketch, it should be quite a familiar piece of code for you by now.

To recreate it you will need:

  • Your standard Arduino setup (computer, cable, Uno or 100% compatible)
  • Seven 560 ohm 1/4 watt resistors
  • DS1307 timer IC circuit components (see this schematic from chapter seven) or a pre-built module
  • Two 74HC595 shift registers
  • Three 74HC4066 quad bilateral switch ICs
  • Solderless breadboard and connecting wires
  • LED clock display module

And here is the result, with red and a blue display.

And the usual board layout:

example12p2boardsmall

The blue looks really good in a dark background. You can also get them in yellow and green.

LEDborder

Moving along. Now and again, you often want to have a few buttons in use for user input, however the cheap ones don’t really like to sit in a breadboard. Naturally, you could make your own “button shield”, which would be very admirable, but then it would be preset to certain pins, which could interfere with your project. I had the same problem in writing this chapter, so came up with this example of an external “button panel” to make life easier. Here is the schematic, nothing complex at all – just four buttons and the required 10k ohm pull-down resistors:

example12p3schematic

and the finished product:

example12p3small

This was a quick job, as I will need to use a few buttons in the near future. Have also put some rubber feet on the bottom to stop the solder joints scratching the surface of the bench. Originally I was going to chop off the excess board at the top, but instead will add some LEDs to it after finishing this article. However using this button board will save a lot of frustration by not trying to jam the buttons into a breadboard.

pinsborder

Exercise 12.1

Now it is time for you to do some work. From this chapter onwards, we will be working on making a small alarm clock – something you could use. Just like the six million dollar man, we have the capability, the technology, and so on … except for Steve Austin. So this chapter, your task is to create and breadboard the  circuit and the underlying sketch. Using the LED display from example 12.1, your clock will have a menu option to set the time, alarm time, turn on and off the alarm, a snooze button – and also switch the display on and off (so you don’t stare at it when you should be trying to sleep).

You could either use a DS1307 module, or the raw parts. For an explanation of the circuitry, please see this post about making a RTC shield. You can always change it when we get to making a real prototype. The same with the Arduino – but for this exercise just stick with the normal board. Later on we will use a bare circuit the same as in chapter ten. With regards to user input, it’s up to you. A rotary encoder could be a real PITA, my example below just uses buttons. Anyhow, off you go!

Parts you will need:

  • Your standard Arduino setup (computer, cable, Uno or 100% compatible)
  • Seven 560 ohm 1/4 watt resistors
  • DS1307 timer IC circuit components (see this schematic from chapter seven) or a pre-built module
  • Two 74HC595 shift registers
  • Three 74HC4066 quad bilateral switch ICs
  • Four normally open buttons or a board as described in example 12.3
  • Solderless breadboard and connecting wires
  • LED clock display module

Here is my interpretation of the answer to the exercise. Although this is a particularly long sketch for our examples, it is broken up into many functions which are quite modular, so you can easily follow the flow of the sketch if you start at void loop(). All of the types of functions used have been covered in the past tutorials. In then next chapters we will add more functions, such an an adjustable snooze, selectable blinking colon, and so on. If you have any questions, please ask.

The buttons have several functions. In normal clock display mode, button one is for menu, two turns the alarm on, three turns it off, and four turns the display on and off. If you press menu, button two is to select time set, three for alarm set, and four is like an enter button. When in the time/alarm set modes, button one increases the hour, button two increases minutes in units of ten, and button three increases minutes in ones, and four is enter. When the alarm activates, button four turns it off.

The schematic is just example 12.2 and example 12.3 connected together, however the first button on the external board is connected to digital pin 8 instead of 1.

So here is a photo of our work in progress:

exercise12p1boardsmall

And a video clip showing the various functions of the clock in operation:

I hope you found success and inspiration in this chapter. Now to Chapter Thirteen.

LEDborder

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

Posted in 4066, 74HC4066, arduino, COM-09117, COM-09481, COM-09483, education, learning electronics, lesson, microcontrollers, tutorialComments (11)

Getting Started with Arduino – Chapter Eleven

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

Welcome back

In this instalment we will start to investigate radio data transmission; then introduce rotary encoders.

As technology has marched along and generally improved on the past, things have been getting small and relatively cheaper. What was once jaw-droppingly amazing is now just meh. But as you are reading this, you know differently. We can now take control of this technology for our own devices. What has been in the past quite unapproachable is now relatively – the concept of wireless data transmission. But no just sending a signal, like a remote-control garage door opener – but sending actual,  useful data – numbers and characters and so on.

How is it so? With this pair of tiny devices:

txrxmodule

Quite small indeed – the pins are spaced 2.54mm apart, and the graph paper is 5mm square. The transmitter is on the right. This pair operates at 315 kHz, over up to a theoretical 150 metres. The data transmission speed is 2400 bps (bits per second). These units are serial passthrough, that is they can replace a link of wire between the serial TX (pin 1) from one Arduino, and the RX of another Arduino (pin 0). They don’t need aerials for very short distances, but the use of one will extend the range towards the maximum. And finally, the transmitter needs between 2 and 10 volts; the receiver 5. Here is the data sheet for these modules: 315MHz.pdf. Normally they are sold individually, for example the transmitter and receiver. You can also find faster (data speed) modules, however we will use these ones today.

In preparation to use these modules, another library needs to be installed – the VirtualWire library. Download the latest revision from the following location: http://www.open.com.au/mikem/arduino/.

There is also a guide to using the library in .pdf format as well. Please note the library author’s instructions with regards to licensing on the last page of the guide. For a refresher on how to install a library, please head back to chapter two. This library will save us a lot of time, it takes care of checking for errors, and only allows complete, correct data (i.e. what is received matches what is sent) to be used in the receiver’s sketch.

However, as wireless is not 100% reliable, you need to take into account that transmissions may not be received, or erroneous ones will be ignored by the receiver’s sketch. You can reduce the data speed to improve reliability and range. Furthermore, you cannot use PWM on D9 and D10 if you are using VirtualWire.

Therefore if you are using this for some important communications, have the transmitter repeatedly sent the message. Later on in this series we will investigate more powerful solutions. Anyhow, moving along …

First of all, we will demonstrate the use of these modules with a basic sketch. It sends some text from one Arduino to another. The receiving Arduino sends the data to the serial monitor box. Of course you could always use an LCD module instead. In my own inimitable style the sketches are very simple, yet allow you to use their contents in your own work. Here is the sketch for the transmitter – tx.pdf and the receiver – rx.pdf.

When working with two sketches at the same time, you can have two Arduinos connected to your PC simultaneously,  just remember to select the correct USB port for the correct Arduino. Do this with the tools > serial port menu option in the IDE. Otherwise you will become very frustrated if you upload the rx sketch to the tx Arduino.

Furthermore, you will need to remove the wire from digital 0 to the data pin on the receiving units before uploading the sketch. And finally, remember to set the serial monitor window at 9600 baud.

Here are my two boards in action:

example11p1small

Although having both boards connected to the one computer is only useful for demonstration purposes, in real life this is obviously useless. Remember that once you upload your sketch the Arduino doesn’t need a computer, only a power supply. You can feed yours between 7 and 12 volts DC through the socket. A nice switchmode power pack will do nicely, or if you are a cheapskate like me, a PP3 battery and clip soldered to a DC plug:

pp3small

You may find that when you use a battery powered Arduino that it basically does not work. Arduino genius Jon Oxer (co-author of Practical Arduino) has found a solution for this issue – place a 10k resistor between GND and digital 0 (RX), or between digital pins 0 and 1. The next thing to consider it improving the reception range. This can be done using two methods – the first by connecting an external antenna, either a length of wire, or perhaps a purpose-built aerial. The second method is to increase the supply voltage of the transmitter up to 12 volts.

Now it is your time to do some work:

Exercise 11.1

You now are able to send characters using the radio link from one Arduino to another. Now it is time to control things remotely. For the purpose of the exercise, we will just control three LEDs, turning them on and off. You already know how to control other things with digital output pins, so we just need to focus on getting the switching on and off. Hint – you can send characters via the wireless link, so create your own codes.

You will need:

  • Two standard Arduino setups (computer, cable, Uno or compatible)
  • two breadboards and some connecting wire
  • One transmitter and one receiver unit
  • three LEDs
  • 3 x 560 ohm 0.25 W resistors. They are to reduce the current to protect the LEDs

Here is the schematic of my interpretation:

exerc11p1sch

… the transmitter:

exer11p1txsmall

… the receiver:

exer11p1rxsmall

and the video:

So how did you go? Hopefully this exercise was easier than you had first expected. If not, here are the example sketches: exercise 11.1 tx and exercise 11.1 rx. A basic transmit/receive system like this would also be handy for testing the range that wireless modules can operate over, or testing a particular site to see if you could implement such wireless modules. It’s always better to test before agreeing to make something for someone.

That concludes our work with radio wireless links – for now.

LEDborder

Next on the agenda is the rotary encoder. Recall how we used a potentiometer in the previous chapters as a dial, to select menu options using the readdial() function. It was simple, cheap and it worked, but some may say it was a kludge. There must be a better way! And there is, with the rotary encoder. A rotary encoder looks like a potentiometer, but it is a knob that can be rotated in either direction infinitely. Furthermore, the knob is also a normally-open button. The encoder we will be using in this chapter is a 12-step encoder, in that you can feel it physically resist rotation slightly twelve times over the 360 degrees of rotation.

Here is our example:

encoder11

On one side there are three pins, and two on the opposing side. On the perpendicular sides are legs for strength, that is they are meant to be soldered into a PCB to lock it in nicely. The problem for us is that those legs interfere when trying to use the encoder in a breadboard, so I have bent them up and cut them off:

encoder2

The pins are easy to understand. The two pins on one side are the button contacts, just like any simple button. The other side with the three pins – the centre goes to ground, and the outside pins are the forwards and backwards output pins. The data sheet for our encoder is here. After fooling about with this all afternoon, the quickest way to get a feel for how it works is with a simple demonstration. So first we will test it out, then see how we can use it in our user-interfaces.

This example is very easy to assemble. You only need an encoder, and the usual Arduino setup. Here is the sketch, and the schematic:

example11p2schem

and in real life:

example11p2boardsmall

and finally a snapshot of the output. Don’t forget to set the speed in your serial monitor box to 115200 baud:

example11p2screen

So as you can see, this is a much better solution that then potentiometer that we used in the past. Plus having the button integrated in the encoder is very convenient, you can really create a user interface with only one control. In the next instalment of this series we will implement the encoder in an existing design. So on to Chapter Twelve.

LEDborder

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

Posted in arduino, COM-09117, learning electronics, lesson, microcontrollers, rotary encoder, tutorial, WRL-10532, WRL-10534Comments (23)

Getting Started with Arduino – Chapter Ten

This is part of a series titled “Getting Started with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the index is here.

In this tutorial we’ll minimise an Arduino Uno board, use time to control – and then find some synergy between the two.

As time goes by, you will want to build projects to use away from the bench, or that are permanent. Although doing so is infinitely fun, it can become expensive if you keep buying Arduino boards for each project or proof-of-concept prototype, or even finished products. However, as always, the Arduino team have solved this problem for us as well. The actual microcontroller integrated circuit (e.g. ATmega328P-PU) can operate with a lot less circuitry than that is contained on your Uno or compatible board. In fact, you can have a functioning Arduino system with three components and a 5V power supply.

How?

To start, please download the Uno schematic from here. Upon glancing at it for the first time, there seems to be a lot of things required. However if you just want to use the digital and analogue pins, you can cut that schematic down to a lot less, however you need to make a couple of changes to how you upload the sketch. Here is what you can get away with:

example10p1schematicsmall

X1 is the 16 MHz resonator. Using only the main circuit on the left, to upload your sketch you need to place the ATmega chip in your Arduino board, upload the sketch, then very carefully remove the chip and place it into your circuit, breadboard, etc. Please make sure to observe anti-static precautions, and always use a chip puller (below):

pullersmall

Furthermore, if you only have one chip, it would be very wise to have a second or third as a backup. A programmed ATmega with the Arduino bootloader can be had for less than US$6. Below is a shot of my barebones Arduino system at work. It is setup to run this basic example:

worksbarebonessmall

The blue and yellow wires run off to a 5 volt power supply. And here is it working:

To recreate this at home, you will need:

  • One ATmega328P-PU microcontroller with Arduino bootrom
  • solderless breadboard
  • 10k ohm resistor
  • 16 MHz resonator
  • (optional – for USB cable) 6-pin header pin
  • (optional – for USB cable) 0.1 uF ceramic capacitor
  • (optional – for USB cable) FTDI cable (the 5 volt version!)

A note about the resonator. Your Arduino board will most likely have a metal crystal, however a resonator is a little cheaper and easier to use, as it has the capacitors in built. If you look at the Arduino schematic, they use a crystal and two 22 picofarad capacitors. So if you use the resonator, pins 1 and 3 go to chip pins 9 and 10, and resonator pin 2 goes to GND. Here is the data sheet for the resonator. They should be easily available, for example from here. The USB cable option will make life a lot easier. The cable is called an FTDI cable, and contains the electronics within to interface between the USB port on your computer and the TX/RX pins on the microcontroller. The wiring details are in the schematic above.

The cable also supplies power whilst programming, or leaving the cable plugged in. Here is my board with the extra wiring connected:

worksftdismall

So if you have this kind of setup, you can just plug the cable into the computer USB port and upload sketches as normal. However there are some modifications that may need to be done with your computer’s operating system to make it work. If you are running Linux or MacOS, please visit here; if you are running windows of some sort, go to device manager, right click the USB serial port you are using, select properties, port-settings tab, advanced, and turn on set RTS on Close.

When purchasing an FTDI cable – make sure you get the 5 volt version!

So now you can integrate the Arduino chip into your prototypes much easier and cheaper. However, if you are going to use SPI or I2C devices, more circuitry will be required. We will examine creating these interfaces in more detail later. A good compromise in this situation is a miniature Arduino-compatible board such as the Freetronics LeoStick.

If you are interested in a project using such a barebones setup, please have a look at blinky the clock.

ic-border

Next on the agenda is a small project to consolidate some previous learning. At the end of chapter nine, we made a (relatively) user friendly clock with an alarm. And in chapter three, we controlled a relay with our arduino. So now we have the ability to create our own on/off timer of which possible uses could be limitless.

In doing so, we can start by modifying the sketch from exercise 9.3. It has the ability to set an alarm time (let’s call it a start time from now on), so we can add the ability to set an end time – it just requires some more variable to store the end time data, and another menu function to set these. Finally, another function is required to check if it is time to turn off (basically identical to the checkalarm() function.

The hardware side of things for the example will be quite simple as well, below is my schematic, and the basic board:

example10p2

example10p2boardsmall

 

 

I am using 12v relays as currently that is all I have in stock. The 12V power supply is just an LM7812 regulator from a 20V DC plugpack. For demonstration purposes any low-voltage relay would be fine. A 5V relay would be perfect as you could run it from the Arduino’s 5V rail.

Note: From here on you understand that one can use an Arduino to switch a very high current and/or voltage with some relays. Please exercise care and consult a qualified, licensed person if you are working with mains voltage (100~250V AC… the stuff that comes out of power points/outlets). They can KILL you!

So for this example, I have modified the sketch as described earlier to accept a start time, end time, and display relevant data on the screen. It will switch on and off the relay, which controls a light globe drawing 100mA – 5 times the current an Arduino digital out pin can deliver. It only operates using 24-hour time, to save user confusion. You could control anything as long as you do not exceed the current and voltage maximums for your particular relay.

So here it is in action. The time has already been set previously, so you can watch the setting of the on/off time, and watch it in action. You can skip ahead from 01:03s to 01:48s to save time.

and here is the sketch for your perusal.

As as example the user interface wasn’t that flash, but naturally it can be worked on to be more intuitive. So now it is your chance to do so, with…

Exercise 10.1

Create a timing system for a hypothetical lighting system that controls two independent circuits. Each timer can turn on or off at a specified time, either daily, only on weekdays, only on a certain day of the week (e.g. only Fridays) or only on weekends. The menu system should be easy and quick to use.

For the purpose of the exercise, you can switch on or off an LED to represent each lighting circuit – you already know how to use the relays.

You will need:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Two usual LEDs of your choice
  • 2 x 560 ohm 0.25 W resistors. For use as current limiters between the LEDs and ground
  • 1 x 10k resistor
  • one push button
  • a breadboard and some connecting wire
  • some water
  • DS1307 timer IC circuit components (see this schematic from chapter seven) or a pre-built module
  • one 10k linear potentiometer
  • LCD module as per chapter two

Here are some videos of my interpretation. To save time I have not connected the LEDs, however timer running status is indicated on the second line of the display – an “!” is shown when a circuit has been activated. The first video shows setting the real time, timer data and displaying the results:

and the sketch.

How did you go? With a little more hardware this exercise could become a real product – you could control sprinkler systems instead of lights, thermostats, anything is really possible. Having a larger LCD screen would help with the user interface, perhaps a 20 character by 4 line unit. As long as such a screen has the standard HD44780 interface, you would be fine. Now on to Chapter Eleven

LEDborder

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

Posted in arduino, barebones, breadboard, education, microcontrollers, relayComments (17)

Getting Started with Arduino! – Chapter Nine

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

Welcome back fellow arduidans!

In this chapter we will start looking at LED matrix displays, designing user interfaces, implementing a user interface for  a clock, and finish up making an alarm clock.

Firstly, let’s have plenty of fun with 64 LEDs! Using an 8×8 LED display module:

ledmatrixsmall

Previously we have used 74HC595 shift registers to drive strips of LEDs, single and four-digit LED displays. An LED matrix seems complex at first, but after further investigation quite simple. With sixteen pins you can control 64 LEDs. It works by having 8 row pins, each pin connected to all the anodes on one row; and 8 pins each connected to the cathodes on one column:

matrixschematic

It does look like a mess, but we can work it out. As we did with the 4-digit 7-segment display module, we just need one shift register for the anodes, and one for the cathodes. Moving along from exercise 6.2, it will be easy to drive the an LED matrix display – one shift register (the left hand side) will apply current to the rows (anodes) and the other shift register will apply current to NPN transistors to allow current to flow from the cathodes (columns) to ground. So we can make an example quite easily. You will need:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • One 8×8 LED matrix. Try to find one that has LEDs with a forward voltage of 2 volts and a current of less than 20mA. If it is bicolour, that’s ok – just use one colour for now
  • Eight 560 ohm 1/4 watt resistors
  • Eight 1 kilo ohm 1/4 resistors
  • Eight BC548 NPN transistors
  • Two 74HC595 shift registers
  • Solderless breadboard and connecting wires

Here is a circuit diagram for our example (click on it to enlarge):

example9p1schematicsmall

Please note that there are eight transistor/resistor combinations from the second shift register – I just have not drawn them in to save my sanity. They’re on the bottom right of my board:

example9p1boardsmall

Now how are we going to light up those LEDs? We need to send two bytes of data to the shift registers, one byte for the row, and one for the column. For this example we will work with individual pixels. For example, say you want to turn on the pixel at 8 across, 8 down – the bottom right. You need to send the following bytes of data to the shift registers: b00000001 and b00000001. In decimal those two numbers are 128 and 128. Or the top-left LED, at 1 across, 1 down – it would be b10000000, b10000000 or decimal 1,1. Once again we can use the functions:

… to send the data to the shift registers. This example sketch for the above circuit should be pretty well self-explanatory if you have been following my tutorials.

Here is is in action:

Once again, quite mesmerising. Did you notice that the horizontal solid rows were dimmer than the solid vertical columns? This is because when you light up one row, all eight LEDs are drawing current from one pin of the shift register – so there is less current for each LED; whereas in the column, each LED has its own source of current, so can therefore operate at full brightness. So a hint – when you are creating images or characters for your display, use scrolling columns to display the image.

Experiment with the example 9.1 sketch, if you display only vertical columns, and make the delay zero – you can give the illusion that the entire display is on, but it is not. Which leads us into the first exercise for this chapter.

Exercise 9.1

We can display entire columns with our matrix display. We can position these columns on demand. And without a delay, fill up the entire matrix. Now you can create images, or characters and display them on the matrix, one column at a time. For example, the little yellow dude from that popular arcade game many years ago might look like this:

Using the circuit described for example 9.1, create a character, shape, or whatever tickles your fancy, and animate it to move across the screen.

Hint – To animate an image, you will need to map the matrix every time the image changes – just like a normal animation or cartoon. However, store all the values for the entire animation in one array, otherwise you will go bonkers. When you need to read the array, each matrix image can be read as they are multiples of eight (then add the reference to the value you want).

For inspiration, here is what I came up with:

and the corresponding sketch.

How did you go? If you have an interesting animation, and you can do so – please email a link to Youtube, Vimeo, etc showing your creation – you could win a prize.

Time to get a little more serious now. 🙁

Over time you have been making things, some useful, some more experimental than anything. Hopefully you will reach the stage of designing something that has a real-world use and could be used by people other than yourself or your immediate circle of friends. In the next few weeks we will look at methods of transitioning projects from prototypes to standalone products you can develop!

A major part of your design should be the user interface, or how your project responds to user input and displays data, results and so on. If something is difficult to use, or understand, it will not be a good product. So what can we do about this? This week we will examine the clock made in example 7.4 and change it to be independent of a computer, and easy for the user to operate. But now for some design inspiration…

The humble alarm clock (it has been staring at me every morning). Here is my late grandfather’s clock from the 1960s:

frontclocksmall

rearclocksmall

Simple, yet functional. It does what it is supposed to do with the minimum of fuss. (It’s German). And that is how our project user interfaces should be. As technical people it is very easy to get carried away and put buttons, lights, and all sorts of things together, but at the end of the day, less is more. How can we emulate this with Arduino – but in a simple method?

Looking at the face of the clock, it displays the time (hours, minutes, seconds) and the alarm time. We can use an LCD for that. On the top is the alarm off button. We can use a button for that. On the rear there are winders for the time and alarm spring – we have electricity for that. There are two knobs, one to adjust the time, and one to adjust the alarm – here we have several options. We could use up/down buttons… perhaps we could use a knob as well? And finally there is the gain control – we don’t need this as our DS1307 is infinitely more accurate.

A rough map of how you want things to work is always a good start, for example my mess below:

uidraftsmall

How can this be implemented? Let’s see. The clock will normally display the date, time, etc. If a button is pressed, it will switch to menu mode (on the right). A knob will be used to select one of the options listed on the right, when the required option is displayed, the user presses the button to select the option. Then the user can use the knob to adjust the variable for that option, and press the button to return to the menu. The last menu option is to return to the clock display. So we can control the whole lot with only one button and one knob.

The button is easy with Arduino, and to save money we can use a potentiometer as a knob. Remember we did this in in exercise 6.2. Normally it can return a value between 0 and 1023, but with our clock we need it to return a value that falls within a variety of ranges – from 0 to 6 for day of the week, to 0 to 59 for the minute adjustment.

Exercise 9.2

Create a function to use a potentiometer to return an integer between zero and a maximum range value. The function will accept the maximum range value, and return an integer which represents the position of the knob. For example:

Here is a short video of my interpretation in action.

And the resulting sketch. The value rangemax that is fed into the function is the number of positions in the range you want to work with. For example, if I want the knob to return a value between zero and fifty-nine (sixty values in the range) I would set rangemax to 60. The value dialpin is the number of the analogue pin the potentiometer is connected to. You should use a linear potentiometer to ensure a nice smooth adjustment.

Great – now we have a way of reading our knob and customising the result for our range requirements. Our clock example’s menu will require eight options, each with their own function (e.g. set hours, set minutes, set year, return to clock, etc). We have one button, so you could use that to trigger an interrupt to start the menu display (interrupts were covered in chapter three). However if you have made an LCD shield use the interrupt pins, you will need to check the button status while displaying the time. We will make the display of the menu a separate function as well.

For now we will make our clock respond to the ‘menu’ button, and display the eight options when the knob is rotated. We will build on the sketch from example 7.4. Here is the result of doing this:

Now it is time (ha!) to make those menu options actually do something. First we need our displaymenu() function to call the selected option. This can be done with a switch…case function. For example, I will put this code after the while loop:

There is no need for a seventh option (return to clock display) as this will default if the knob is in the ‘7’ range. Notice I have already declared the name of the functions to call. All we have to do is create the individual functions. However there is one catch to work around, when it comes to setting time and date data, this is all done with the one function:

So inside the function that (for example) sets the hour, immediately before setting the hour, read the rest of the values from the clock, and reset them back in with the setDateDS1307() function.

Once again the basic work has been done for you, please see this video:

… and the sketch. Although the contents of the LCD during the menus may be brief, the framework of the user interface has been created and can now be easily modified. For example, if you had a 20 x 4 character LCD, you could offer more help to the user. But returning to the original task – emulating Grandfather’s alarm clock. We need an alarm!

Exercise 9.3

You guessed it – modify the clock in example 9.3 to have an alarm as well. User can set the alarm, and turn it on or off with the menu system. When the alarm sounds, the user should be able to turn off the alarm, Have fun!

How did you go? Here is a video demonstration of my work:

… and the sketch. That was really fun – I have a lot more clock ideas now.

I hope you enjoyed the change of pace this article and have a greater understanding on why we should create simpler human-machine interfaces wherever possible. Now to move on to Chapter Ten.

LEDborder

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

Posted in arduino, education, LED matrix, lesson, microcontrollers, tutorialComments (41)

Getting Started with Arduino! – Chapter Eight

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

In this chapter we will continue to examine the features of the DS1307 real time clock, receive user input in a new way, use that input to control some physical movement, then build a strange analogue clock. So let’s go!

Recall from chapter seven, that the DS1307 is also has an inbuilt square wave generator, which can operate at a frequency of 1Hz. This is an ideal driver for a “seconds” indicator LED. To activate this you only need to send the hexidecimal value 0x10 after setting the date and time parameters when setting the time. Note this in line 70 of the solution for exercise 7.1. This also means you can create 1Hz pulses for timing purposes, an over-engineered blinking LED, or even an old-school countdown timer in conjunction with some CMOS 4017 ICs.

For now, let’s add a “seconds” LED to our clock from Exercise 7.1. The hardware is very simple, just connect a 560 ohm resistor to pin 7 of our DS1307, thence to a normal LED of your choice, thence to ground. Here is the result:

Not that exciting, but it is nice to have a bit more “blinkiness”.

Finally, there is also a need to work with 12-hour time. From the DS1307 data sheet we can see that it can be programmed to operate in this way, however it is easier to just work in 24-hour time, then use mathematics to convert the display to 12-hour time if necessary. The only hardware modification required is the addition of an LED (for example) to indicate whether it is AM or PM. In my example the LED indicates that it is AM.

Exercise 8.1

So now that is your task, convert the results of exercise 7.1 to display 12-hour time, using an LED to indicate AM or PM (or two LEDs, etc…)

Here is my result in video form:

and the sketch.

OK then, that’s enough about time for a while. Let’s learn about another way of accepting user input…

Your computer!

Previously we have used functions like Serial.print() to display data on the serial monitor box in the Arduino IDE. However, we can also use the serial monitor box to give our sketch data. At first this may seem rather pointless, as you would not use an Arduino just to do some maths for you, etc. However – if you are controlling some physical hardware, you now have a very simple way to feed it values, control movements, and so on. So let’s see how this works.

The first thing to know is that the serial input has one of two sources, either the USB port (so we can use the serial monitor in the Arduino IDE) or the serial in/out pins on our Arduino board. These are digital pins 0 and 1. You cannot use these pins for non-serial I/O functions in the same sketch. If you are using an Arduino Mega the pins are different, please see here.  For this chapter, we will use the USB port for our demonstrations.

Next, data is accepted in bytes (remember – 8 bits make a byte!). This is good, as a character (e.g. the letter A) is one byte. Our serial  input has a receiving buffer of 128 bytes. This means a project can receive up to 128 bytes whilst executing a portion of a sketch that does not wait for input. Then when the sketch is ready, it can allow the data to serially flow in from the buffer. You can also flush out the buffer, ready for more input. Just like a … well let’s keep it clean.

Ok, let’s have a look. Here is a sketch that accepts user input from your computer keyboard via the serial monitor box. So once you upload the sketch, open the serial monitor box and type something, then press return or enter. Enter and upload this sketch:

 

Here is a quick video clip of it in operation:

So now we can have something we already know displayed in front of us. Not so useful. However, what would be useful is converting the keyboard input into values that our Arduino can work with.

Consider this example. It accepts a single integer from the input of serial monitor box, converts it to a number you can use mathematically, and performs an operation on that number. Here is a shot of it in action:

example8p2

If you are unsure about how it works, follow the sketch using a pen and paper, that is write down a sample number for input, then run through the sketch manually, doing the computations yourself. I often find doing so is a good way of deciphering a complex sketch. Once you have completed that, it is time for…

Exercise 8.2

Create a sketch that accept an angle between 0 and 180, and a time in seconds between 0 and (say) 60. Then it will rotate a servo to that angle and hold it there for the duration, then return it to 0 degrees. For a refresher on servo operation, visit chapter three before you start.

Here is a video clip of my interpretation at work:

So now you have the ability to generate user input with a normal keyboard and a PC. In the future we will examine doing so without the need for a personal computer…

Finally, let’s have some fun by combining two projects from the past into one new exercise.

Exercise 8.3

Create an analogue clock using two servos, in a similar method to our analogue thermometer from chapter three. The user will set the time (hours and minutes) using the serial monitor box.

Here is a photo of my example. I spared no expense on this one…

exercise8p3small

Here is a video demonstration. First we see the clock being set to 12:59, then the hands moving into position, finally the transition from 12:59 to 1:00.

If you had more servos and some earplugs, a giant day/date/clock display could be made… Nevertheless, we have had another hopefully interesting and educational lecture. Or at least had a laugh. Now onto chapter nine.

LEDborder

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

Posted in arduino, education, LCD, lesson, microcontrollers, serial monitor, servo, tutorialComments (17)

Let’s make an Arduino LCD shield

In this short tutorial we make an Arduino LCD shield.

Updated 18/03/2013

Today we are going to make an Arduino shield with an LCD module. More often than not I have needed to use an LCD shield in one of my projects, or with the Arduino tutorials. Naturally you can buy a pre-made one, however doing your own is always fun and nice way to pass an afternoon. Before we start, let me say this: “to fail to plan is to plan to fail”.  That saying is very appropriate when it comes to making your own shields.

The first step is to gather all of the parts you will need. In this case:

  • an LCD module (backlit if possible, but I’m being cheap and using a non-backlit module) that is HD44780-compatible
  • a 10k linear trimpot, used to adjust the LCD contrast
  • a blank protoshield that matches your Arduino board
  • various header pins required to solder into the shield (they should be included with your protoshield)
  • plenty of paper to draw on

For example:

p1070040small

Next, test your parts to ensure everything works. So, draw a schematic so you have something to follow:

lcdshieldschematic

And then build the circuit on a solderless breadboard, so you can iron out all the hardware bugs before permanently soldering into the shield. If you have a backlit LCD, pins 15 and 16 are also used, 15 for backlight supply voltage (check your data sheet!) and 16 for backlight ground:

p1070043small

Once connected, test the shield with a simple sketch – for example the “HelloWorld” example in the Arduino IDE. Make sure you have the library initialization line:

filled with the appropriate parameters. If you’re not sure about this, visit the LCD display tutorial in my Arduino tutorials.

Now to make the transition from temporary to permanent. Place your components onto the protoshield, and get a feel for how they can sit together. Whilst doing this, take into account that you will have to solder some jumper wires between the various pads and the digital pin contacts and the 5V strip at the top row, as well as the GND strip on the bottom row. You may find that you have to solder jumper wires on the bottom of the shield – that’s fine, but you need to ensure that they won’t interfere with the surface of your Arduino board as well.

Furthermore, some protoshields have extra functions already added to the board. For example, the shield I am using has two LEDs and a switch, so I will need to consider wiring them up as well – if something is there, you shouldn’t waste the opportunity to not use them. If your shield has a solder mask on the rear, a great way to plan your wiring is to just draw them out with a whiteboard marker:

p1070045small

 

Remember to solder these wires in *before* the LCD … otherwise you will be in a whole world of pain. The LCD should be soldered in second-last, as it is the most difficult thing to desolder if you have made any mistakes. The last items to solder will be the header pins. So let’s get soldering…

p1070046small

After every solder joint, I pushed in the LCD module – in order to check my placement. You can never check too many times, even doing so I made a small mistake. Having a magnifying glass handy is also a great idea:

p1070047small

Now just to soldier on, soldering one pad at a time, then checking the joint and its relationship with where it should be on the board. Be very careful when applying solder to the pads, they can act as a “drain” and let lots of solder flow into the other side. If this happens you will spend some time trying to remove that excess solder – a solder sucker and some solder wick is useful for this.

Finally all the wires and pads were connected, and I checked the map once more. Soldering in the LCD was  the easiest part – but it is always the most difficult to remove – so triple check your work before installing the display. Now it was time to sit in the header sockets, and test fit the shield into my arduino board. This is done to make sure there is sufficient space between the wires on the bottom of our shield and the top of the arduino:

p1070049small

Even though you wouldn’t normally put a shield on top of this shield, I used the header sockets to allow access to all of the arduino pins just in case. Soldering the sockets was easy, I used blu-tack to hold them into place. Crude but effective.

p1070053small

And we’re finished. Soldering is not the best of my skills, so I checked continuity between the pins on the LCD and where they were supposed to go, and also electrically checked for bridges between all the soldered pins to check for shorts. A multimeter with a continuity buzzer makes this easy. Naturally I had a short between LCD pin 14 and 13, but some solder wick helped me fix that. So electrically it was correct… time to see if it actually worked! At this point it is a good idea to clear up the workspace, switch off the soldering iron, put it somewhere safe to cool down, then wash your hands thoroughly. Here are some photos of the finished product on my arduino board:

p1070054small

 

p1070055small

As we’re using a Freetronics protoshield with onboard LEDs, the only thing to do was alter the demonstration sketch to take account for the pin placements, and insert some code to blink the LEDs.

I never need an excuse to make a video clip, so here is the result:

So there you have it. With a little planning and care, you too can make your own Arduino shield. An LCD shield would be useful for everyone, as they are great for displaying data and requesting input, yet quite fiddly to use with a solderless breadboard. 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.

Posted in arduino, education, HD44780, LCD, projects, shield, tutorialComments (0)

Getting Started with Arduino! – Chapter Seven

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

Welcome back fellow arduidans!

This week is going to focus around the concept of real time, and how we can work with time to our advantage. (Perhaps working with time to our disadvantage is an oxymoron…) Once we have the ability to use time in our sketches, a whole new world of ideas and projects become possible. From a simple alarm clock, to complex timing automation systems, it can all be done with our Arduino and some brainpower. There is no time to waste, so let’s go!

First of all, there are a few mathematical and variable-type concepts to grasp in order to be able to understand the sketch requirements. It is a bit dry, but I will try and minimise it.

The first of these is binary-coded decimal.

Can you recall from chapter four how binary numbers worked? If not, have a look then come back. Binary coded decimal (or BCD) numbers are similar, but different… each digit is stored in a nibble of data. Remember when working with the 74HC595 shift registers, we sent bytes of data – a nibble is half of a byte. For example:

bcdtable

Below is a short clip of BCD in action – counting from 0 to 9 using LEDs:

However, remember each digit is one nibble, so to express larger numbers, you need more bits. For example, 12 would be 0001 0010; 256 is 0010 0101 0110, etc. Note that two BCD digits make up a byte. For example, the number 56 in BCD is 0101 0110,  which is 2 x 4 bits = 1 byte.

Next, we will need to work with variables that are bytes. Like any other variable, they can be declared easily, for example:

byte seconds = B11111;

B11111 is 31 in base 10, (that is, 2^4+2^3+2^2+2^1+2^0     or    16+8+4+2+1)

However, you can equate an integer into a byte variable. Here is a small sketch demonstrating this. And the result:

example7p1

If you printed off the results of the sketch in example 7.1, it would make a good cheat sheet for the Binary Quiz program in Chapter Five.

Anyhow, moving forward we now take a look at hexadecimal numbers. ‘Hex’ numbers are base-16, in that 16 digits/characters are used to represent numbers. Can you detect a pattern with the base-x numbers? Binary numbers are base-2, as they use 0 and 1; decimal numbers are base-10, as they use 0 to 9 – and hexadecimal numbers use 0 to 9 then A to F. Run the following sketch to see how they compare with binary and decimal.

Below is a screenshot of the result: the left column is binary, the centre decimal, and the right hexadecimal:

example7p1

Unfortunately the IC we use for timing uses BCD, so we need to be able to convert to and from BCD to make sense of the timing data. So now we have an understanding of BCD, binary, base-10 decimal, bytes, hexadecimal and nibbles. What a mouthful that was!

Coffee break.

Before we head back to timing, let’s look at a new function: switch… case. Say you needed to examine a variable, and make a decision based on the value of that variable, but there were more than two possible options. You could always use multiple if…then…else if functions, but that can be hard on the eyes. That is where switch… case comes in. It is quite self-explanatory, look at this example:

OK, we’re back. It would seem that this chapter is all numbers and what not, but we are scaffolding our learning to be able to work with an integrated circuit that deals with the time for us. There is one last thing to look at then we can get on with timing things. And that thing is…

The I2C bus.

(There are two ways one could explain this, the simple way, and the detailed way. As this is “Getting Started with Arduino”, I will use the simple method. If you would like more detailed technical information, please read this document: NXP I2C Bus.pdf, or read the detailed website by NXP here)

The I2C bus (also known as “two wire interface”) is the name of a type of interface between devices (integrated circuits) that allows them to communicate, control and share data with each other. (It was invented by Philips in the late 1970s. [Philips spun off their semiconductor division into NXP]).  This interchange of data occurs serially, using only  two wires (ergo two wire interface), one called SDA (serial data) and the other SCL (serial clock).

nxpi2cbussmall

I2C bus – image from NXP documentation

A device can be a master, or a slave. In our situation, the Arduino is the master, and our time chip is the slave. Each chip on the bus has their own unique “address”, just like your home address, but in binary or in hexadecimal. You use the address in your sketch before communicating with the desired device on the I2C bus. There are many different types of devices that work with the I2C bus, from lighting controllers, analogue<> digital converters, LED drivers, the list is quite large. But the chip of interest to us, is the Maxim DS1307 Serial I2C real-time clock. Let’s have a look:

ds1307small

This amazing little chip, with only a few external components, can keep track of the time in 12-and 24-hour formats, day of week, calendar day, month and year, leap years, and the number of days in a month. Interestingly, it can also generate a square wave at 1Hz, 4kHz, 8kHz, or 32 kHz. For further technical information, here is the DS1307 data sheet.pdf. Note – the DS1307 does not work below 0 degrees Celsius/32 degrees Fahrenheit, if you need to go below freezing, use a DS1307N.

Using the DS1307 with our Arduino board is quite simple, either you can purchase a board with the chip and external circuitry ready to use, or make the circuit yourself. If you are going to do it yourself, here is the circuit diagram for you to follow:

  ds1307exampleuse
 

The 3V battery is for backup purposes, a good example to use would be a CR2032 coin cell – however any 3V, long-life source should be fine. If you purchase a DS1307 board, check the battery voltage before using it…. my board kept forgetting the time, until I realised it shipped with a flat battery. The backup battery will not allow the chip to communicate when Vcc has dropped, it only allows the chip to keep time so it is accurate when the supply voltage is restored. Fair enough. The crystal is 32.768 kHz, and easily available. The capacitor is just a standard 0.1uF ceramic.

Now to the software, or working with the DS1307 in our sketches. To enable the I2C bus on Arduino there is the wire library which contains the functions required to communicate with devices connected to our I2C bus. The Arduino pins to use are analogue 4 (data) and analogue 5 (clock). If you are using a Mega, they are 20 (data) and 21 (clock). There are only three things that we need to accomplish: initially setting the time data to the chip; reading the time data back from the chip; and enabling that 1Hz square-wave function (very useful – if you were making an LED clock, you could have a nice blinking LED).

First of all, we need to know the I2C address for our DS1307. It is 0x68 in hexadecimal. Addresses are unique to the device type, not each individual device of the same type.

Next, the DS1307 accepts or returns the timing data in a specific order…

  • seconds (always set seconds to zero, otherwise the oscillator in the DS1307 will stay off)
  • minutes
  • hours
  • day of week (You can set this number to any value between 1 and 7, e.g. 1 is Sunday, then 2 is Monday…)
  • day of month
  • month
  • year
  • control register (optional – used to control the square-wave function frequency and logic level)

… but it only accepts and returns this data in BCD. So – we’re going to need some functions to convert decimal numbers to BCD and vice-versa (unless you want to make a BCD clock …)

However, once again in the interests of trying to keep this simple, I will present you with a boilerplate sketch, with which you can copy and paste the code into your own creations. Please examine this file. Note that this sketch also activates the 1Hz square wave, available on pin 7. Below is a quick video of this square wave on my little oscilloscope:

This week we will look at only using 24-hour time; in the near future we will examine how to use 12-hour (AM/PM) time with the DS1307. Here is a screen capture of the serial output box:

example7p3

Now that you have the ability to send this time data to the serial output box, you can send it to other devices. For example, let’s make a simple LCD clock. It is very easy to modify our example 7.3 sketch, the only thing to take into account is the available space on the LCD module. To save time I am using the Electronic Brick kit to assemble this example. Below is a short clip of our LCD clock operating:

and here is the sketch. After seeing that clock fire up and work correctly, I felt really great – I hope you did too.

Update – for more information on the DS1307 real-time clock IC, visit this page

Now let’s head back in time, to when digital clocks were all the rage…

Exercise 7.1

Using our Arduino, DS1307 clock chip, and the exact hardware from exercise 6.2 (except for the variable resistor, no need for that) – make a nice simple digital clock. It will only need to show the hours and minutes, unless you wish to add more display hardware. Have fun!

Here is my result, in video form:

and the sketch. Just an interesting note – after you upload your sketch to set the time; comment out the line to set the time, then upload the sketch a second time. Otherwise every time your clock loses power and reboots, it will start from the time defined in the sketch!

As mentioned earlier, the DS1307 has a square-wave output that we can use for various applications. This can be used from pin 7. To control the SQW is very easy – we just set the pointer to the SQW register then a value for the frequency. This is explained in the following sketch:

And here it is in action – we have connected a very old frequency counter to pin 7 of the DS1307:

And there we have it – another useful chapter. Now to move on to Chapter Eight.

LEDborder

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

Posted in arduino, BCD, ds1307, education, hexadecimal, I2C, LCD, lesson, microcontrollers, tutorialComments (35)

Getting Started with Arduino! – Chapter Six addendum

Welcome back fellow arduidans!

After reviewing Chapter Six of our tutorials, I felt that there was some important information missing about the section regarding driving 4-digit 7-segment LED display modules. Although we have discussed displaying numbers using the module, and hopefully you have done this yourself with exercise 6.2, those numbers were constantly being written to the display as the sensor was being repeatedly read.

But how do we send a number to the display – and hold it there? We need a function that can accept the number to display – and the length of time (in cycles) to hold it there. I have rewritten the function displaynumber() from the solution to exercise 6.2 – now it accepts another value, “cycles”. This is the number of times the number will be shown on the display.

Here is a sketch to demonstrate this function, the hardware is the same as exercise 6.2, except there is no need for the variable resistor.

And my day wouldn’t be complete without another video demonstration. This example has cycles set to 500.

So there you have it! Now you have the knowledge to use these multi-digit displays effectively. And now that we have mastered them, we can move onto more interesting and useful display types. In the meanwhile, off to Chapter Seven.

LEDborder

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

Posted in arduino, education, lesson, microcontrollers, tutorialComments (0)

We now have a Google Group!

Hello readers

I would like to announce the opening of our own tronixstuff discussion email list via Google Groups: http://groups.google.com/group/tronixstuff

Through this group we can discuss posts, projects, products and anything else mentioned on the tronixstuff or related websites. For the time being it will be moderated until we get going and see what the level of conversation is like. However, please feel free to ask questions, offer suggestions, or make constructive criticism about anything in the tronixstuff world.

It is also meant for support with any of the Arduino tutorials or products mentioned in the blog. I will do my best to help you, so don’t be afraid to ask!

However it is not for spam, discrimination, attacking others, or blatantly selling things.

screenshot

So sign up now!

http://groups.google.com/group/tronixstuff

Posted in about, education, learning electronics, projects, tutorialComments (0)

Getting Started with Arduino! – Chapter Six

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!

Hello once again to our regular Arduino tutorial instalment. In this chapter we are up to all sorts of things, including: distance sensing, using prototyping shields, even more shiftiness with shift registers and 4-digit 7-segment displays, and some exercises to refresh and expand your knowledge. Wow – let’s get cracking…

Do you know how to keep your distance? Some people do, some do not. The same goes for mechatronical things (i.e. robots, those little autonomous vacuum cleaners, etc). So to solve that problem you can integrate a distance sensor into your design. Hopefully by following this section you will gain an understanding of such sensors, and be able to make use of them later on in your own projects. Anyhow, today we are looking at the Sharp GP2Y0A21YK0F infra-red distance sensor. What a mouthful… The funny thing is that it looks like a robot head:

sharpsensorsmall

That white JST connector is for three leads, +5V, GND, and analogue out. When purchasing it you should also get a matching lead to save time and mucking about.

How it works is quite simple (I must stop writing that, some things are not as simple as they seem…) – the sensor contains an infra-red transmitter and a receiver. It returns a voltage that is relative to the distance between itself and the object in front of it. This output voltage is inversely proportional to the distance; which is explained better with this graph from the data sheet:

voltagedistance

However it is always fun to test these things out yourself. So I placed a sensor up over my desk, measured out 80cm, and attached the multimeter to the analogue output of the sensor:

sensorchecksmall

A crude setup but effective. I held a white piece of cardboard in front of the sensor, starting from more than one metre away, then moved closer to the minimum, then back out again. As shown in this video clip:

Although watching that multimeter may not have been too interesting, hopefully the next task will be!

Exercise 6.1

Using the values from the graph from the Sharp data sheet (above), make yourself a distance-measuring device. Use an LCD module to display the measurements. Metric and imperial! This shouldn’t be too hard at all, you’re just using one analogue input from the sensor, some basic maths, and displaying some data on an LCD. Furthermore, to make it truly portable, you could wire up a 9v PP3 battery to a DC plug and use it for power. A hint – before calculating distances, run a sketch to just return the analogRead() value from the sensor. Then you can make your own judgement on voltage-distance calculations. To save time I used the Electronic Bricks to rapidly construct this prototype.

You will need:
  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • One parallel LCD display module
  • One Sharp infra-red distance sensor and sensor cable
  • a breadboard and some connecting wire

Anyhow, here is a photo of what I came up with:

exercise6p1small

and the ubiquitous video clip

Finally, my sketch for the solution. You may have to adjust the values in the decision tree for more accuracy. After spending some time with this sensor, I wouldn’t rely on it for exact distance calculations, however it would be very useful for general item detection, air switches and so on. In the next week or two we will examine another type of distance sensor.

What else could this be used for? Robotics sensors, burglar alarms, switching things on and off. Hopefully you have gained some knowledge about this sensor and have some ideas for implementation.

LEDborder

Now that we have spent a few weeks constructing our prototypes on breadboards and electronic bricks, it is now time to look at how we can do this in a more compact, and/or permanent method. As you already know, the Arduino system allows for “shields”, PCBs that plug on top of your Arduino board to add some sort of extra functionality. One of these was the Electronic Brick chassis, another popular shield is the Ethernet shield.

Moving on…

In previous instalments we have worked with 7-segment LED displays, using up to three at once, being controlled by 74HC595 shift registers. As you may have realised by now that involved a lot of wiring, resistors, time and effort. But what if you need four or more digits? Use an LCD… Maybe. Sometimes you need to use LED displays for aesthetic reasons, price, clarity, or just because you love that LED look. Thankfully you can find four digit displays, instead of having to use 2 x 2 or 4 x 1 digit displays. Let’s have a look at one now:

4dig7segsmall

For the newcomer there would be a surprising lack of pins on this display module. That is a good thing, and a slightly tricky thing – but we can overcome the obstacles and use it very easily. How? Again, with two 74HC595 shift registers and some brainpower. Firstly, let’s have a look at the pins – from left to right they are: E, D, C, G, F, B, A, C1, C2, C3, C4, decimal point, unused, unused. This display is common cathode, so to display (for example) the number 1 on digit 3, you would apply ~+2 volts to pins 6 and 7, and attach ground to pin 10. Very much the same as using a single-digit display, except you need to choose the cathode that corresponds with the digit you wish to use. In this tutorial we are using a Common Cathode unit. Out of curiosity’s sake, here is the data sheet for the module used in this chapter: data sheet.pdf.

Secondly, how are we going to control the cathodes with out Arduino? Current comes out of a cathode, so it would not accept a signal from our digital out pins. What we need to do is have a simple switch on each cathode between the display pin and ground, so we can control which digit we want to use. How can we do this with our Arduino? Easy… we can use a simple NPN transistor as a switch. Remember we did this with a relay in chapter three!

But using 4 digital out pins for cathode control is a waste of pins, we can use our trusty shift register again to control the cathodes. So that means we need two shift registers in total, the first to control the digit (0~9), and the second to switch on the cathode of the position we wish to display our digit in. Time to do it!

The first (left-hand) shift register from the Arduino controls the segments on the display, via 560 ohm resistors. Just like last time. The second (right-hand) shift register controls the cathodes. Pins Q0~Q3 connect to the base of a BC548 transistor via a 1k ohm resistor. The collector of the transistor is connected to the cathode on the display, and the emitter to ground. For example:

example6p1schematicsmall

Note that the schematic above is a guide only. But here it is in real life, below:

example6p1small

After a few projects, wiring up displays and shift registers should be a lot quicker for you now. Here is the matching sketch I came up with for the demonstration video below.

You’d have to admit, even in the year 2010, LED displays still look mesmerising. Or maybe that’s just me! Here is the data sheet display.pdf for the LED display I used. You can use other ones,as long as they are common cathode; just match the LED element pins with your first shift register, and the cathode pins with the second shift register.

But on to making something useful…

Exercise 6.2

Using the hardware from example 6.1 above, create a device that displays the value of an analogue sensor. For example, if we connect a 10k variable resistor to an analogue input, the Arduino will return a reading of between 0 and 1023. From a hardware perspective, all you need to do is add an analogue sensor (e.g. LDR, 10k variable resistor, the infra-red sensor from earlier on, etc.). The software will be a little tricky, but if you completed exercise 5.1, or 5.2 you shouldn’t have a problem at all. As you will be displaying one digit at a time, but very quickly, try to minimise the number of times you clear the display – in doing so you will keep the brightness at a maximum.

You will need:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • One 4-digit, 7-segment LED display, common cathode
  • Two 74HC595 shift registers
  • Four BC548 or equivalent NPN transistors
  • 8 x 560 ohm 0.25 W resistors. For use as current limiters between the LED display segments and ground
  • One 10k variable resistor
  • a breadboard and some connecting wire

For motivation, here is a video clip of my result. There are two examples, one with leading zeroes, and one without:

And the sketch as well.

That wasn’t too hard was it? Now that you can use such a display, it will become easier to display output from your various projects. Now on to Chapter 6A.

LEDborder

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

Posted in arduino, distance sensor, education, gp2y0a21yk0f, infrared, IR, lesson, microcontrollers, sharp, tutorialComments (31)

Getting Started with Arduino! – Chapter Five

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

Welcome back fellow arduidans!

Hello once again to our weekly Arduino instalment. This week are up to all sorts of things, including: more shiftiness with shift registers, more maths, 7-segment displays, arduinise a remote control car, and finally make our own electronic game! Wow – let’s get cracking…

In the last chapter we started using a 74HC595 shift register to control eight output pins with only three pins on the Arduino. That was all very interesting and useful – but there is more! You can link two or more shift registers together to control more pins! How? First of all, there is pin we haven’t looked at yet – pin 9 on the ‘595. This is “data out”. If we connect this to the data in pin (14) on another ‘595, the the first shift register can shift a byte of data to the next shift register, and so on.

Recall from our exercise 4.1, this part of the sketch:

If we add another shiftOut(); command after the first one, we are sending two bytes of data to the registers. In this situation the first byte is accepted by the first shift register (the one with its data in pin [14] connected to the Arduino), and when the next byte is sent down the data line, it “pushes” the byte in the first shift register into the second shift register, leaving the second byte in the first shift register.

So now we are controlling SIXTEEN output pins with only three Arduino output pins. And yes – you can have a third, fourth … if anyone sends me a link to a Youtube clip showing this in action with 8 x 74HC595s, I will send them a prize. So, how do we do it? The code is easy, here is the sketch. On the hardware side, it is also quite simple. If you love blinking LEDs this will make your day. It is the same as exercise 4.1, but you have another 74HC595 connected to another 8 LEDS. The clock and latch pins of both ‘595s are linked together, and there is a link between pin 9 of the first register and pin 14 of the second. Below is a photo of my layout:

example5p1small

and a video:

Can you think of anything that has seven or eight LEDs? Hopefully this photo will refresh your memory:

ch57seg_small

Quickie – if you want to find out the remainder from a quotient, use modulo – “%”. For example:

a = 10 % 3;

returns a value of 1; as 10 divided by 3 is 3 remainder 1.

and

If you need to convert a floating-point number to an integer, it is easy. Use int();. It does not round up or down, only removes the fraction and leaves the integer.

Anyhow, now we can consider controlling these numeric displays with our arduino via the 74HC595. It is tempting to always use an LCD, but if you only need to display a few digits, or need a very high visibility, LED displays are the best option. Furthermore, they use a lot less current than a backlit LCD, and can be read from quite a distance away. A 7-segment display consists of eight LEDs arrange to form the digit eight, with a decimal point. Here is an example pinout digram:

7segpinout

Note that pinouts can vary, always get the data sheet if possible.

Displays can either be conmmon-anode, or common-cathode. That is, either all the LED segment anodes are common, or all the cathodes are common. Normally we will use common-cathode, as we are “sourcing” current from our shift register through a resistor (560 ohm), through the LED then to ground. If you use a common-anode, you need to “sink” current from +5v, through the resistor and LED, then into the controller IC. Now you can imagine how to display digits using this type of display – we just need to shiftout(); a byte to our shift register that is equavalent to the binary representation of the number you want to display.

Huh?

Let’s say we want to display the number ‘8’ on the display. You will need to light up all the pins except for the decimal point. Unfortunately not all 7-segment displays are the same, so you need to work out which pinout is for each segment (see your data sheet) and then find the appropriate binary number to represent the pins needed, then convert that to a base-10 number to send to the display. I have created a table to make this easier:

example5p2pintable

And here is a blank one for you to print out and use: blank pin table.pdf.

Now let’s wire up one 7-segment display to our Arduino and see it work. Instead of the eight LEDs used in exercise 4.1 there is the display module. For reference the pinouts for my module were (7,6,4,2,1,9,10,5,3,8) = (a,b,c,d,e,f,g,DP, C, C) where DP is the decimal point and C is a cathode (which goes to GND). The sketch: example 5.2. Note in the sketch that the decimal point is also used; it’s byte value in this example is 128. If you add 128 to the value of loopy[] in the sketch, the decimal point will be used with the numbers.

example5p2small

and the video:

There you go – easily done. Now it is time for you to do some work!

Exercise 5.1

Produce a circuit to count from 0 to 99 and back, using two displays and shift-registers. It isn’t that difficult, the hardware is basically the same as example 5.1 but using 7-segment displays.

You will need:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Two 7-segment, common-cathode displays
  • Two 74HC595 shift registers
  • 16 x 560 ohm 0.25 W resistors. For use as current limiters between the LED display segments and ground
  • a breadboard and some connecting wire
  • some water

You are probably wondering how on earth to separate the digits once the count hits 10… a hint: 34 modulo 10 = 4. 34 divided by 10 = 3.4 … but 3.4 isn’t an integer. While you are thinking, here is the shot of my layout:

exercise5p1small

and the ubiquitous video:

And here is the sketch for my interpretation of the answer.

I hope you have gained more of an understanding of the possibilities available with shift registers. We will continue with more in the next tutorial.
Exercise 5.2

Once again it is your turn to create something. We have discussed binary numbers, shift registers, analogue and digital inputs and outputs, creating our own functions, how to use various displays, and much more. So our task now is to build a binary quiz game. This is a device that will:

  • display a number between 0 and 255 in binary (using 8 LEDs)
  • you will turn a potentiometer (variable resistor) to select a number between 0 and 255, and this number is displayed using three 7-segment displays
  • You then press a button to lock in your answer. The game will tell you if you are correct or incorrect
  • Basically a “Binary quiz” machine of some sort!

I realise this could be a lot easier using an LCD, but that is not part of the exercise. Try and use some imagination with regards to the user interface and the difficulty of the game. At first it does sound difficult, but can be done if you think about it. At first you should make a plan, or algorithm, of how it should behave. Just write in concise instructions what you want it to do and when. Then try and break your plan down into tasks that you can offload into their own functions. Some functions may even be broken down into small functions – there is nothing wrong with that – it helps with planning and keeps everything neat and tidy. You may even find yourself writing a few test sketches, to see how a sensor works and how to integrate it into your main sketch. Then put it all together and see!

You will need: (to recreate my example below)

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • Three 7-segment, common-cathode displays
  • eight LEDs (for binary number display)
  • Four 74HC595 shift registers
  • 32 x 560 ohm 0.25 W resistors. For use as current limiters between the LED display segments and ground
  • a breadboard and some connecting wire
  • 10k linear potentiometer (variable resistor)
  • some water

For inspiration here is a photo of my layout:

exercise5p2small

and a video of the game in operation. Upon turning on the power, the game says hello. You press the button to start the game. It will show a number in binary using the LEDs, and you select the base-10 equivalent using the potentiometer as a dial. When you select your answer, press the button  – the quiz will tell you if you are correct and show your score; or if you are incorrect, it will show you the right answer and then your score.

I have set it to only ask a few questions per game for the sake of the demonstration:

And yes – here is the sketch for my answer to the exercise. Now this chapter is over. Hope you had fun! Now move on to Chapter Six.

 

Posted in 74hc595, arduino, education, hardware hacking, lesson, microcontrollers, tutorialComments (17)

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.

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.

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:

74hc595

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.

binary12

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.

binary2

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)

74hc595pinouts

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:

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:


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:

ex4p1layoutsmall

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:

soundmachine_small

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:

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:

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)

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:

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

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

will change our array to

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:

Will change alter our array to become

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

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:

ex4p2layoutsmall

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.

LEDborder

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

Posted in 74hc595, arduino, education, lesson, microcontrollers, tronixstuff, tutorialComments (17)

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 huge Arduino tutorial which is fun, easy and interesting. The first chapter starts here.

Posted in arduino, education, lesson, tutorialComments (4)

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.

Posted in arduino, lesson, microcontrollers, relay, servo, tutorialComments (5)

Getting Started with Arduino! – Chapter Two

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

I hope you have been enjoying these posts and learning and creating and making many things. 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:

TMP36

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:

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:

example2point1small

And here is the sketch:

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:

 

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

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!
LEDborder
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
  • a 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:

ex2p2boardsmall
… 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.

LEDborder

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

Posted in arduino, LCD, lesson, microcontrollers, tmp36, tutorialComments (40)

Getting Started with Arduino! – Chapter One

Welcome to Chapter One.

Updated 24/11/2012

I hope you have been enjoying your new-found skills with the Arduino system, and enjoying Massimo’s book. There are many interesting tasks for you to complete in this instalment: finish chapter four and five of the book, which contains some vital information about electricity; we’ll look at a new command or two for your sketches that will save you time and a lot of sketch memory; take a look at pulse width modulation (huh?); go random!; receive inputs from analogue sources; make some decisions; and finally – complete a project as an exercise for you to test your new knowledge.

First of all, please continue on from page 38 until the end of chapter four. This contains excellent instuctions on how to deal with “switch-bounce”, which is vital for future use. See you soon!

Hello again.

Recall from the previous instalment that your exercise involved a lot of repeated commands to light each LED in sequence – for example:

That seemed repetitive and time consuming – the nemesis to the reasoning for the existence of Arduino! However the solution can be found by using the for command. The purpose of the for command is to repeat a section of your sketch a number of times (of course this number is an integer – you cannot repeat a loop 3.141 times!).

Below is a very basic example that blinks an LED on pin 9 five times:

What is happening here is this:

  • the integer “wow” is set to have a value of one
  • the code in the curly brackets is executed
  • the code checks to ensure “wow” is less than or equal to five, then increments “wow” by one

You can also use “wow–” to subtract one from the value of wow, or another variable. Anyway, if wow <=5  the looping continues; and if wow>5 it stops and the sketch moves on.

Hopefully by this stage you have recognised how this can simplify the code for exercise 0.1 from the last instalment. No? Let’s try that now. So instead of that huge block of code to light the LEDS in order up and down, rewrite it to use two loops – one for the up direction, and one for the down.

How did you go? Here’s what we came up with:

 

Well, wasn’t that better? Those for loops saved us a lot of time, and the use of variables also allows for sketch modifications to be much easier that hunting for each value to change within the sketch.

Groovy. Time for a quickie:

Hey, do you need a random integer? Easy!

random(x) returns a random integer between 0 and x-1. For example, if you need a random number between 0 and 255, use random(256). However, using random() is not entirely random, you need to seed the random number generator inside your Arduino chip. Use randomSeed(analogRead(0)); or another open analogue pin. You can also specify a range, for example random(10,20) will produce a random number between 10 and 19 (the minimum of the range is inclusive, the maximum exclusive – that is why the range is 10~19.

Next on the agenda is pulse-width modulation. Instead of reinventing the wheel, you will now work through chapter five of the book until the end of page 62.

Now that you have emulated a popular cult’s computer, it’s time to have some real fun with PWM and colours. Massimo mentioned about using red, green and blue LEDs to make any colour in the spectrum. This can be done quite easily (like most things) with your Arduino! When you were in school in art classes, you may remember that red + yellow = orange, red + green = blue, and so on. You can achieve the same effect using LEDs, and also vary the brightness between them to create the entire colour spectrum.

First, let’s look at how the primary colours can be used to create all sorts of colours. This example demonstrates briefly the possibilities of experimenting with red, green and blue.

You will need:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • A diffused (not clear plastic) common-cathode RGB light emitting diode. A diffused LED will shine like a light bulb, where a clear one will just look like a 5mm dot.
  • 2 50 ohm 0.25 W resistors. They are to reduce the current to protect the green and blue LED section
  • 1 150 ohm 0.25W resistor. This is to reduce the current to the red LED section
  • a breadboard and some connecting wire
  • a camera (optional) – to document your success!

The circuit is quite simple, however the pins of the LED can be tricky. Here is the explanation of their layout:

rgbdata

The resistors are between the PWM output pins and the colour anode of the LED. See the board layout below:

example1point2small

And here is the code… oops sketch:

And here it is in action! Mesmerising…

Wasn’t that fun? I hope you enjoyed that as much as I did writing about it for you. Don’t stare at the LED for too long though… we’re moving on to analogue sensors! Follow the book until the end of page 69. Now for something completely different. It is time to learn about a new command: if…else. 

More often than not your sketch will need to make a decision. Is a switch on? Or is it off? If the variable ph equals 8657309 I will send that number to the GSM module to dial the number! Once again, with Arduino – it’s simple.

Example: if the value of temperature is greater than 100, turn off pin 13, otherwise turn it on.

You can also extend this with else if…

Example: if the value of temperature is greater than 100, turn off pin 13; otherwise if value of humidity > 80, turn on pin 7.

With the if…else statement you have a choice of six operators:

  • == equals
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to
  • != not equal to

At this point go and have a break and some fresh air. Because after that, it’s time for…

Exercise 1.1

Now we want to put together all the things learned so far and make something that has analogue inputs, digital outputs, and lots of LEDs… a voltmeter! Imagine a bar graph of ten LEDs, each one represents a voltage range. The range of the voltmeter will be between 0 and 10 volts DC – ideal for testing batteries and cells before they head to the garbage bin.

That sounds like a lot of work (the sketch, not throwing away batteries), but it isn’t when you break it down into smaller tasks. Let’s have a think about it…

We know that analogRead() can measure between 0 and 5 volts, and return an integer between 0 and 1023 relative to the measurement. Ah, but we want to measure up to 10 volts. Easy – use a voltage divider. Use two small resistors of equal value (e.g. 560 ohm 0.25 watt).

Next, how to convert that analogRead() value to represent a voltage we relate to an LED. We know that it will return a value between 0 and 1023, in our case that relates to 0~10 volts. So each LED will relate to one-tenth of the maximum reading. So the first LED will need to be illuminated if the analogRead() returns between 0 and 102.3 (actually 102 as it returns integers, not real numbers). The second LED will need to be illuminated if analogRead() returns between 103 and 205. Etcetera.

Now the rest should be easy… use your new sketch decision-making skills to decide which LED to light up (and don’t forget to turn it off as well) and you’re away…

You will need:

  • Your standard Arduino setup
  • ten LEDs of your choice. Standard ones are fine, or perhaps a mixture of colours?
  • 3 x 560 ohm 0.25 W resistors. One to reduce the current to protect the LED indicator in use, and two for the voltage divider
  • 1 x 10k ohm 0.25 W resistor. For use with the analogue input
  • a breadboard and some connecting wire
  • a camera (optional) – to document your success!

So here is our layout diagram:

exer1p1

And here it is in real life:

ex1point1_small

 

… and the action movie! We connected a variable power output to the voltmeter for the sake of the demonstration …

… however due to resistor tolerance and other analogue electrical problems caused by using a breadboard, our voltmeter was a little overenthusiastic. So like any quality piece of test equipment, it required some calibration. There are two ways this could be achieved:

  • put a variable resistor in the voltage divider. Then feed a known source, such as 5V from an LM7805 regulator, then adjust the variable resistor until LED 5 was constantly on;
  • put another voltmeter (e.g. a multimeter) over the voltage input to measure the voltage being measured by our voltmeter; use the serial.begin and serial.println() functions (from page 69) to send the value of voltage to the screen. Adjust the voltage being measured until you hit 1, 2, … 10V – noting the serial output. Then substitute these values into the if…then decision tree for the LEDs.

The second method is more accurate and easier to accomplish, so I have inserted the serial code into the example sketch below.

Here is a clip showing the results of the second calibration option:

So how did you go? Did it work first time? It’s ok if it didn’t, as you learn by doing and fixing your mistakes. Remember – if you have any questions, leave a comment at the bottom of this post and I will get back to you. But to save you time, here is the sketch. So there you have it. Today you have learned many more useful things to help you on your Arduino journey. And now for Chapter Two.

LEDborder

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

Posted in arduino, lesson, microcontrollers, RGB LED, tutorialComments (8)

Getting started with Arduino! – Chapter Zero

Hello world!

Updated 24/11/2012

Please join with us as we learn about electronics and the Arduino! Together through this series of tutorials I would like to share with you a journey of learning, exploration and fun with the Arduino system, and make some enjoyable, useful, interesting, useless and practical things. These posts will be published on a regular basis, on top of the other non-micro controller posts. Instead of listening to someone talking really quickly on a video, you can read and follow through at your own pace, see examples in action, learn a great deal – and be inspired to make something of your own.

So let’s get started…

There are over fifty chapters in this series, however you should start here (chapter zero). However there is a full  index of articles is to your right, or can be found here. Once you have covered the material in chapters zero to thirteen you should be able to jump into any other chapter. During the first few posts, we will refer to the book:

and also assume a basic knowledge of electronics. For support or to have your questions answered, post your enquiry in our Google Group – a friendly place for such discussions.

If you would prefer an off-line method of learning, or would like a great book on the topic – consider my book “Arduino Workshop” – it’s the best book on the market for a complete beginner to learn about Arduino.

First of all, let’s breakdown the whole system into the basic parts. From there we can build an understanding of what Arduino is all about.

Arduino is an open source physical computing platform based on a simple input/output board and a development environment that implements the Processing language (www.processing.org). Arduino can be used to develop standalone interactive objects, or be connected to software on your computer. [1]

So, we have hardware and software. Our hardware will be a personal computer that can run the Arduino IDE (integrated development environment) software; and the Arduino itself and the electronics to go with it.

Our software is the IDE – software very similar to a word-processor, but can send the Arduino program (or “sketch”) to the micro controller. These sketches are programs that are written in the processing language – which is similar to C. These are interpreted by a boot loader – software in the chip that allows it to understand your sketch. As the Arduino system is open source, anyone can purchase a blank micro controller and put the boot loader on it, or even write their own boot loader or modify the original one.

Now for the Arduino itself. But what do we mean by that? Let’s have a look…

Arduino Uno

What we have is a microcontroller installed into a circuit board with a USB interface, a DC power socket, and many input and output lines (more about them later). Plus some LEDs for status reports, and other miscellaneous components. This board is the Uno, and uses the ATMega328 micro controller.

There are also larger, smaller, older and in the future newer boards – each different by their physical size, interface type, and available sketch and data memory. A very good improvement on the Arduino boards are available from Freetronics.

The purpose of the board is to simplify to a great degree access to the micro controller, and allow you to easily interface with inputs, outputs, add power supply, connect to a PC for programming, and talk to other circuits. However the board is more for your convenience, you can actually use the programmed micro controller in your own designs without the board. 

To summarise at this point – with an Arduino you can connect various forms of input and output, and create a program to process and respond to the inputs and outputs. For example, you could create a temperature alarm – when your room temperature rises above a set amount, the Arduino could sound an alarm.

Forms of input can include: buttons, switches, movement sensors, temperature sensors, light sensors, gas sensors (!), dials that you can turn (e.g. like a volume knob), wireless data receivers, etc. Forms of output can include: lights, noise-makers, motors, pumps, other circuits, liquid-crystal displays, etc. Basically anything that can be switched on or off, or controlled by electricity, can be controlled by an Arduino.

To make things easier, you can buy or make what is called a shield. This is an interface board that sits on top of your Arduino, and has various types of circuitry you can interface with. For example, an Ethernet network connection, a joystick for games or controlling a robot, or an LCD.

So that means with the right sketch, and the right hardware interface, and maybe a shield, you can do almost anything.

Great!

Thankfully that’s about all we need to learn at the moment. Now it is time to actually do something. You are going to need three things:

  • A personal computer running Linux, MacOS or Windows with a USB port, with Internet access. Then again, if you’re reading this – you’re on the ‘net
  • a USB cable that matches your board socket
  • an Arduino or compatible board. Most boards should come with a USB cable, check before buying.
Update – 10/01/2013: I have written these tutorials in a period spanning over two years. During this time several versions of the Arduino IDE have been published. Over the next few weeks I am endeavouring to update the tutorials so that they work with the latest Arduino v1.0.1 (or newer) IDE. In the meanwhile, you can run both v23 (old) and v1.0.1 (and more) on the same machine. Any tutorial noted as updated on 24/11/2012 or later works with the new IDE. Any questions – email john at tronixstuff dot com.

And now for the initial preparation – please install your Arduino IDE software using the instructions here. If you are running Ubuntu, here is an excellent installation guide.

How did you go? Did your LED blink? Were you mesmerised by it, staring blankly at all the blinky goodness? It’s ok, you can admit it – we all were the first time.

When working through this series of tutorials, some of the files you download will end with .pde or .ino. They’re both fine, the .pde extension was used for sketches written before Arduno IDE v1.0. You can load these and work with them as normal.

At this point I hope you realised that the Arduino can be powered by your computer’s USB port. However, if you want to use your programmed Arduino away from the computer, you will need a nice regulated plugpack or another source of power.

There is some really basic things to get started, however with respect to the Arduino creators, please refer to the book Getting Started with Arduino book until the end of page 38. You should be able to get that LED to blink on your own!

Exercise 0.1

Now let’s have some more blinky fun. Do you remember Knight Rider with David Hasselhoff? The ‘hoff drove a tricked-up Trans Am with some cool lights in the bonnet, a horizontal row with each light blinking in sequence from left to right to left…

Your mission, is to simply recreate this with your Arduino, using not one but eight LEDs. Blink them in an endless loop in the sequence 1-2-3-4-5-6-7-8-7-6-5-4-3-2-1-2-3-… with a delay of one second.

You will need:

  • Your standard Arduino setup (computer, cable, Uno or compatible)
  • 8 light emitting diodes (LEDs). Anything as long as they draw less than 40mA.
  • 8 560 ohm 0.25 W resistors. They are to reduce the current to protect the LEDs
  • a breadboard and some connecting wire
  • a camera (optional) – to document your success!

Hint – make the delay a variable so you can alter it easily.

From your original flashing LED project in the book, the digital pin 13 was used. This time, you can use digital pins 2 to 9. The hardware side is easy – run a wire from each digital output pin to the anode of an LED, then put a 560 ohm resistor from the cathode back to ground. See the diagram below:

exercise0p1

And this is what the result should hopefully look like:

And of course, here it is in action:

Now it is your turn to do something – write the code! But before you do that, plan what you want to do first (some old-schoolers would call the plan an algorithm). For example, for this exercise you might write something like…

exercise 0.1 plan

set all the pins I want to use as outputs
create a variable to store the delay duration in milliseconds
start an infinite loop
turn on pin 2, wait for delay duration, turn it off
turn on pin 3, wait for delay duration, turn it off
repeat for pins 4 to 9
then do the same thing but backwards down to pin 3
end of infinite loop

So how did you go? Did it work first time? It’s ok if it didn’t, as you learn by doing and fixing your mistakes. Remember – if you have any questions, leave a comment at the bottom of this post and I will get back to you. But to save you time, here is the sketch:

So there you have it. Today you have learned how to set up a computer to program your Arduino, and written some sketches to create outputs based on your design. Although it wasn’t that much, we have to start somewhere… but great things will follow. Like chapter one! 

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.

Notes:

[1] from “Getting Started with Arduino” by Massimo Banzi (O’Reilly).

Posted in arduino, basic, book, lesson, microcontrollers, tutorialComments (15)


Subscribe via email

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: