Tag Archive | "microcontrollers"

Kit Review – Snootlab Rotoshield

Hello Readers

[Update: 11/12/11 – Added example code and video]

In this article we will examine yet another product from a bundle sent for review by Snootlab, a Toulouse, France-based company that in their own words:

… designs and develops electronic products with an Open Hardware and Open Source approach. We are particularly specialized in the design of new shields for Arduino. The products we create are licensed under CC BY-SA v3.0 (as shown in documents associated with each of our creations). In accordance with the principles of the definition of Open Source Hardware (OSHW), we have signed it the 10th February 2011. We wish to contribute to the development of the ecosystem of “do it yourself” through original designs of products, uses and events.

Furthermore, all of their products are RoHS compliant and as part of the Open Hardware commitment, all the design files are available from the Snootlab website.

The subject of the review is the Snootlab Rotoshield – a motor-driver shield for our Arduino systems. Using a pair of L293 half-bridge motor driver ICs, you can control four DC motors with 256 levels of speed, or two stepper motors. However this is more than just a simple motor-driver shield… The PCB has four bi-colour LEDs, used to indicate the direction of each DC motor; there is a MAX7313 IC which offers another eight PWM output lines; and the board can accept external power up to 18V, or (like other Snootlab shields) draw power from a PC ATX power supply line.

However as this is a kit, let’s follow construction, then explore how the Rotoshield could possibly be used. [You can also purchase the shield fully assembled – but what fun would that be?] Assembly was relatively easy, and you can download instructions and the schematic files in English. As always, the kit arrives in a reusable ESD bag:

There are some SMD components, and thankfully they are pre-soldered to the board. These include the SMD LEDs, some random passives and the MAX7313:

Thankfully the silk-screen is well noted with component numbers and so on:

All the required parts are included, including stackable headers and IC sockets:

It is nice to not see any of the old-style ceramic capacitors. The people at Snootlab share my enthusiasm for quality components. The assembly process is pretty simple, just start with the smaller parts such as capacitors:

… then work outwards with the sockets and terminals:

… then continue on with the larger, bulkier components. My favourite flexible hand was used to hold the electrolytics in place:

… followed with the rest, leaving us with one Rotoshield:

If you want to use the 12V power line from the ATX socket, don’t forget to bridge the PCB pads between R7 and the AREF pin. The next thing to do is download and install the snooter library to allow control of the Rotoshield in your sketches. There are many examples included with the library that you can examine, just select File > Examples > snootor in the Arduino IDE to select an example. Function definitions are available in the readme.txt file included in the library download.

[Update]

After acquiring a tank chassis with two DC motors, it was time to fire up the Rotoshield and get it to work. From a hardware perspective is was quite simple – the two motors were connected to the M1 and M2 terminal blocks, and a 6V battery pack to the external power terminal block on the shield. The Arduino underneath is powered by a separate PP3 9V battery.

In the following sketch I have created four functions – goForward(), goBackward(), rotateLeft() and rotateRight(). The parameter is the amount of time in milliseconds to operate for. The speed of the motore is set using the Mx.setSpeed() function in void Setup(). Although the speed range is from zero to 255, this is PWM so the motors don’t respond that well until around 128. So have just set them to full speed. Here is the demonstration sketch:

… and the resulting video:

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

As always, thank you for reading and I look forward to your comments and so on. Furthermore, don’t be shy in pointing out errors or places that could use improvement. Please subscribe using one of the methods at the top-right of this web page to receive updates on new posts, follow on twitterfacebook, or join our Google Group.

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

Posted in arduino, I2C, kit review, L293, MAX7313, microcontrollers, motor shield, product review, rotoshield, snootlabComments (5)

Tutorial – Arduino Uno and SM5100B GSM Cellular

Shield is now obsolete. Contact your hardware supplier for support.

Posted in arduino, CEL-00675, CEL-09607, cellphone hacking, cellular, GSM, lesson, SMS, tronixstuff, tutorial

Initial review: mbed LPC1768 Development Board

In this article we review the mbed NXP LPC1768 development board and the mbed system in general.

Introduction

Today we will examine the mbed NXP LPC1768 development board. The goal of the mbed system is to “provide(s) a platform for microcontroller hardware, tools, libraries and resources designed to enable rapid prototyping with microcontrollers.” (http://mbed.org/handbook/About). Personally I also see this as a good option for a “next step” for those who have outgrown their Arduino – the mbed offers much more processing power, a similar development environment and similar hardware ease of use. A great way to move from 8-bit to 32-bit power…

The NXP LCP1768 MCU on our mbed board offers the following specifications:

  • a Cortex-M3 core running at 96MHz
  • 512kb flash memory and 64kb RAM
  • powered via USB or 4.5~9V DC applied straight to the board
  • Real time clock (requires external battery backup if necessary)
  • Loads of I/O options, including:
  • USB serial
  • I2C
  • Ethernet on board
  • SPI
  • serial I/O
  • Control-area network (CAN) bus
  • 3.3v digital logic, 40mA per digital pin with a total maximum of 400 mA
  • analog and digital I/O pins

For a full description and data sheet, please visit: http://mbed.org/handbook/mbed-NXP-LPC1768.

Although a small project started by two ARM employees, the mbed has proven to be a worthy product to allow people of generally all skill levels access to powerful microcontrollers without a lot of the inherent complications. It does this in two ways:

Firstly, the hardware is very simple and designed for ease of use. The LPC1768 is mounted on a small board to convert it to a DIP format, making breadboard easy. The designers have also thought to include four blue LEDs for digital output and a nice large reset button. Interface with the PC is via USB. The mbed appears as a USB flash drive to your computer’s operating system, and compiled programs are downloaded as a single .bin file into the mbed.

Secondly, the development environment. Unlike other MCU products on the market, mbed is a completely online development environment. That is, in a manner very similar to cloud computing services such as Google Docs or Zoho Office. However there are some pros and cons of this method. The pros include not having to install any software on the PC – as long as you have a web browser and a USB port you should be fine; any new libraries or IDE updates are handled on the server leaving you to not worry about staying up to date; and the online environment can monitor and update your MCU firmware if necessary. However the cons are that you cannot work with your code off-line, and there may be some possible privacy issues. We will examine the online environment later on.

Preparing and using the mbed is incredibly simple. The designers have certainly exceeded their goal of providing a rapid prototyping environment. The process from opening the box to running your first program is (as always) quite simple.

The initial packaging is clear and inviting, and includes a getting started document, USB cable, a laminated hardware pinout card (very useful) and a bumper sticker (!):

1

 

The mbed unit itself is compact yet not too small:

2

The underside contains the USB interface and flash drive controllers:

3

The initial setup requires registration with the mbed online environment. This is done by plugging in your mbed to the USB, and visiting the web page URL stored in the mbed’s flash drive:

4

This will take you to the login page where you can create a new user profile:

5

The serial number of the mbed is recognised and linked to your user account. This means you do need to own an mbed to explore the depths of the online services available, and also serves to keep the mbed online ecosystem free of spammers and whatnot. After registration, you will be presented with the “getting started” page, which contains links to the function references, tutorials, FAQs, user forums, user-contributed content and more. All is revealed by exploring the links from this page.

After signing up, you can create a profile page which is public. This also contains tabs that contain notes, published (programs you make public) and libraries (that you have made public) Initially I thought the profile page would be private, or limited to other mbed owners, but this is not the case. From this page you can create notebook files, view your past activity and display published programs and libraries.

For example, I created a test notebook page and someone left a comment on it twenty minutes later. So be careful if you have some secrets – instead, you could cut and paste work to and from the IDE. However if you accidentally publish something it can be deleted, but remember that the internet is written in ink, not pencil.

However don’t let privacy worries put you off – just be careful not to write anything or publish programs you want to keep secret. Furthermore, as said earlier –  having an online IDE has a few advantages – you don’t need to install anything on your PC apart from an up to date web browser. This means you can work on programs from other computers with ease. Bored at work? Using a locked-down hotel or  school computer? You can still work on your mbed programs!

The openness of the mbed environment does create a positive, helpful environment similar to that found in the open-source community – there are many libraries that have been submitted that allow connection to various pieces of hardware such as LCD screens, bluetooth, Wii controllers, motors, servos, sensors and so on – as well as libraries for pachube, twitter, HTTP client and server access, and much more. These are found in the environment’s “Cookbook” section. If something interesting is on the market, there may very well be an mbed library to work with it.

The IDE is quite clear and straightforward. The program editor maintains colour-context, line numbering, support auto-formatting, and you can import or export code using the standard copy and paste keyboard shortcuts.

6

You can have multiple folders open at once, where each folder contains one program, the standard mbed function library and others you may have imported. Furthermore, there is also a very clear function reference for the standard mbed library available within the IDE – very useful. Programs are written in C++, and the online IDE takes care of everything – leaving you with only the .bin file to upload to the mbed. If you are new to programming or a little rusty with C++, books with unfortunate titles such as “C++ for Dummies” may prove useful.

7

You can also import libraries published by other mbed users into your own projects. Details of these published libraries (and programs) are listed in the mbed online environment. The speed of development is demonstrated very well in this video from the mbed team:

The support options are very good, including a members-only forum, loads of information, the Cookbook, a wiki for publishing user-contributed libraries and resources, and other FAQs and so on. If you have a question I am sure it could be answered very quickly.  When it comes time to compile and run your program, after a successful compile your computer will download a single .bin file, which is then copied over to your mbed. Then by pressing the reset button on the mbed, the program is stored into the MCU and executed. You can store more than one .bin file on the mbed, however the latest file (by time stamp) is only executed.

Overall the mbed is a refreshingly-easy point of entry to microcontrollers. The ability to quickly prototype an idea into reality is really not difficult, and those with some C++ experience (or willing to learn) will make use of the mbed environment in no time at all. And if you decide to move your prototype into production, details and schematics are provided to help implement the nxp LPC1768 into your designs. Frankly, for fast prototyping at work, or just fun for anyone interested in electronics, the mbed offers a simple yet powerful way of getting things done.

The mbed board used in this review was a promotional consideration from RS. You can purchase an mbed directly from your local RS distributor.

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 learning electronics, lesson, LPC1768, mbed, microcontrollers, product review, review, tronixstuff, tutorialComments (10)

Project – The “Kid-e-log”

With this project you can build an RFID time-clock system to keep track of employees, children and more.

Updated 18/03/2013

Recently I was listening to a friend who has three teenage children, of whom needed to arrive home before their parent. Unfortunately the parent needs to work all day and arrives home in the evening, and they lamented not being able to check when the children had arrived home.

After a few hours it occurred to me that a simple time clock would solve her problem – each child could check-in upon arriving home, and the parent could review the check-in times later on. And thus the kid-e-log was born.

From a hardware perspective, it would be quite simple. An LCD screen, RFID reader and some tags, and a real time clock IC such as a Maxim DS1307 – all running from the ubiquitous Arduino board. After some contemplation it occurred to me that smart kids might try to mess up the hardware by pulling the power, so it also uses an EEPROM to store time data which is impervious to power loss, and the kid-e-log will not have any user buttons. After initial programming for time and RFID key data, any changes will need to be effected by the programmer (i.e. me).

If RFID is new to you, review my Arduino tutorials before moving forward.

Before jumping ahead and making something, we discussed exactly what the function would be. Each child would have an RFID tag, and when it is read the hardware will save the arrival time in memory, and display it on the LCD. The time data will be reset automatically at 0400h or by reading an RFID card belonging to the parent. There will not be any buttons, and the hardware must be power-failure resistant – therefore EEPROM memory is needed for time data and a backup battery for the real-time clock.

From a hardware perspective, the requirements are quite simple:

  • An Arduino-style board of some sort (we used the Freetronics Eleven)
  • Maxim DS1307 or DS3232 real-time clock IC
  • Microchip 24LC256 EEPROM
  • Usual 16 character, 2 line LCD with HD44780-compatible interface
  • 125kHz RFID reader with serial output, and four RFID tags (don’t get the Weigand version!)
  • Two 4.7 kilo ohm resistors (for I2C bus with EEPROM)
  • Two 0.1 uF ceramic capacitors (for power smoothing on the breadboard)
  • a solderless breadboard for prototyping
  • a nine volt DC power adaptor, rated for no less than 300 milliamps
  • And for the final product, a nice enclosure. More on that later…

The DS1307 and the EEPROM are both using the I2C bus, and the RFID reader (more information) uses Arduino digital pin zero (serial input).  The LCD is pretty straight forward as well, as described in the tutorials.

Here is the schematic for the prototype hardware:

schematicss

From a software (sketch) perspective, the design is easily broken up into distinct functions which makes programming quite easy. The sketch is a basic loop, which follows as such:

  • check to see if a tag is read by the RFID reader – if so, branch to the the reading function (which compares the read tag against those on file, and records the time matching the tag to the EEPROM)
  • display real time, date and check-in data on the LCD – another function
  • delay for a moment to stop the LCD flickering from fast updating
  • check if the time is 4am, and if so call a function to reset the check-in times

From each of those four main instructions, functions are called to handle various tasks. For example the displayData() funtion is used to read the DS1307 real time clock, and display the time and date on the top line of the LCD. Then it reads the contents of the EEPROM, and displays the check in time for each RFID tag – or a line if they have not checked in yet.

The data stored in the EEPROM is held in following order

  • tag 1 status (0 for not checked in, 1 for checked in)
  • tag 1 check-in hour
  • tag 1 check-in minute

and repeats for tag two and three. You will notice in the sketch that the RFID cards’ serial data are stored in individual arrays. You will need to read your RFID cards first with another sketch in order to learn their values. The rest of the sketch should be quite easy to follow, however if you have any questions please ask.

You can download the sketch from here. Next for the hardware. Here is our prototype, ready for action:

prototypess

And now for a short video clip of the prototype kid-e-log in operation:


Notice how removing the power does not affect the real time nor the stored check-in data. Almost child-proof. The final task was to reassemble the prototype in order to fit into a nice enclosure. Unfortunately by this stage the person concerned had moved away, so I had no need to finish this project. However I had already purchased this nice enclosure:

enclosuress

It was just large enough to accept the Eleven board, and protoshield with the EEPROM and RFID reader circuitry, and the LCD module. It is custom-designed with mounts for Arduino boards and the LCD – a perfect fit. However the use of it can wait for another day. So an important note to self – even if designing things for a friend – get a deposit!

Such is life. I hope you enjoyed reading about this small project and perhaps gained some use for it of your own or sparked some other ideas in your imagination that you can turn into reality.

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, I2C, projects, rfid, time clock, tronixstuff, tutorialComments (3)

Project – Let’s make Electronic Dice

In this project we make electronic dice.

Updated 18/03/2013

In this article you can learn how to make an electronic die (die is the singular of dice), using an ATmega328 with Arduino bootloader and a few inexpensive components. The reason for doing this is to introduce another object that you can build, learn from and be proud of. It is a fairly simple procedure, and at the end you will have something that is useful for a long time to come. Again this article will be a design-narrative, so please read it in full before making a die yourself.

First of all, here is a photo of my finished product.

finishedssss1

Naturally the cosmetic design is up to you, I have used this box, LEDs and switches as they were already in my stock of parts. The die is quite a simple design – with a twist. Inside the unit is a mercury switch. This consists of a small glass tube with two wires at one end and a small amount of mercury. When the mercury rolls over the wires, they are shorted out. Just like a push button when it is pushed, for example:

tiltdemoss

 

We will make use of this switch to start the die “rolling” – to simulate the use of a non-electronic, under-engineered wooden die. For safety, I will be using a mercury switch that is enclosed with plastic:

tiltswitchss

Over the last few years several people have contacted me saying “don’t use mercury switches”. Fair enough, if you don’t want to either, use element-14  part number 540614.

First of all, the circuit is assembled on a breadboard using our Eleven Arduino-compatible board. There is no need to build the complete independent circuit yet, as we just want to test the aspects of the sketch, and try various LEDs out. I have some bright blue ones which match with the blue housing:

bboard1ss

There is a function in the sketch (below) called

which is used to display the numbers 1 to 6. The following video is a demonstration of this:

The sketch is quite simple – you can download it from here. Once the behaviour of the die met my expectation, I used my ZIF-socket programming board to upload the sketch into a nice fresh ATmega328 with bootloader. One could also add a piezo buzzer for sound effects, as described in sketch. This will end up being a birthday present for a young niece, so I have omitted the sound effects.

Next,  time to rebuild the circuit on the breadboard – using the bootrom and not our Eleven. Here is the schematic:

dieschematicss

and the resulting layout:

prototypess

And it works! Things are starting to come together now. As usual I was curious about the current draw, as this helps me determine how long the battery will last. On standby it draws between 10 and 20 milliamps, and between 30 and 40 milliamps when displaying numbers.

By now you probably would like to see it work, so here is the prototype demonstration:

Now it is your turn… from a hardware perspective, we will need the following:

  • IC1 – ATmega328 with Arduino bootloader programmed with the sketch
  • IC2 – LM78L05 voltage regulator – note that with the front facing you, pins are 1-output, 2-GND, 3-input
  • D1-D7 – LEDs of your choosing
  • R1, R9: 10 kilo ohm resistors
  • R2-R8: 560 ohm resistors
  • X1 – 16 MHz resonator – centre pin to ground, outside pins to IC1 pins 9 and 10
  • small piece of protoboard
  • SW1 – on/off button
  • SW2 – mercury tilt switch
  • 9V PP3 battery and snap
  • optional – 28-pin IC socket
  • a nice case, but not too large
  • some thin heatshrink
  • some sponge or insulating foam which has a width and length slightly larger than the protoboard

The ideal housing would be one that fits in the palm of your hand. However, such miniaturisation levels are quite difficult in the home workshop. The biggest problem (literally) was the power supply. The only battery with the voltage and a decent amp-hour rating was the 9V PP3. Alkaline models are usually good for 500 to 625 mAh, and should power the die for about ten hours of continuous use. Furthermore, whilst running the prototype on the breadboard, it would function down to 6 volts, however the LEDs were a little dim – but still perfectly usable. However I managed to squeeze it all in – sans the IC socket.

So if you are like me, and soldering the IC in directly – make sure you are happy with your sketch!

Anyhow, time to start the hardware work of assembly. Using veroboard/protoboard is easy if you plan things out first.

Remember – to fail to plan is to plan to fail

So in this case, I like to get some graph paper and draw out the tracks with a highlighter, such as:

templatess

My diagram shows the tracks as they would be on the rear of the veroboard. With this, using a pencil one can mark out component placement, links, and where to cut tracks if necessary. Those long lines are great for +5V and ground. Etcetera. When you have laid out the parts, go and have a break. Return and check your work, then fire up your iron and go!

Once completed you then have an easy to follow plan to solder along with. Here is the above example after I finished soldering:

after

After the soldering was completed, and the board checked for any shorts or poor-quality joints – it was time to have a clean-up and clear the mess away. Now it was time to stuff the whole lot into the housing… but it would be prudent to test the circuit beforehand. So I soldered in the tilt switch, and the battery snap, connected the battery – and it worked. Notice in the image below the placement of the centre LED – I have used some heatshrink over the legs to totally insulate them, and have it at the centre of the board:

almostdoness

Now to focus on the enclosure. In order to keep the costs down I used a box (and almost everything else) from my existing stock. It turned out to be a little small, but with some creative squeezing everything would fit. The PCB and battery are separated by a thin layer of anti-static foam, to prevent the possibility of the sharp edges of the PCB underside scratching the label of the battery and causing a short.

The final messy task was to drill the holes for the LEDs and the power switch. The switch was easy enough, just knock a small hole in then use a tapered reamer to get the exact size:

switchholess

Then to drill the holes in the lid for the LEDs to poke through. Easily done, just be sure to mark where you want the holes to be before drilling. Furthermore, you need to get the LEDs as far through the holes as possible:

ledsholess

Then the final step before sealing the lot up is to get the power wires soldered to the switch and the battery snap:

beforelidss

When you are putting everything in the box, make sure the tilt switch is tilted so that when the die is at rest, the tilt switch is laying in the off position. Otherwise the die will just merrily repeat forever until you turn it off.

finishedssss1

And of course, an action video:

Once again I hope that this demonstration has shown how easy it is for anyone with some spare time and the knowledge from my Arduino tutorials can create something from scratch.

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, atmega328, dice, games, projects, tutorialComments (4)

Let’s make another Arduino LCD shield

In this tutorial we make an LCD shield for using 20 character by four row LCD modules with Arduino Uno.

Updated 18/03/2013

In this article you can follow the process of making another LCD shield for the Arduino Uno or compatible boards. In the past (which explains the word another in this title) I made a 16 x 2 character LCD shield, however it was not backlit, nor large enough. Recently I acquired a 20 x 4 character backlit LCD for use in my Arduino tutorials, therein making this project necessary. To refresh your memories, here is the original shield:

p1070054small

However this time, I cannot mount the display on the shield, it is just too large. Furthermore, it is preferable to be able to stack other shields on top of the new LCD shield. Therefore the display will be external and connected with lengths of wire. So time to get cracking. The first step was to assemble all the parts together. The new LCD has a standard 16-pin  HD44780 interface, and is very easy to connect:

partssm

What we have: one 20×4 character backlit LCD, a Freetronics basic protoshield, some stacking pin headers, a button, 10k ohm trimpot for contrast adjustment, and some spacers and matching screws to give the LCD some legs. Afterwards I got some 0.1uF ceramic capacitors as well, to smooth supply current on the 5V rail of the shield. Here is the data sheet for the LCD: 2004 LCD.pdf.

As usual the first thing to do was to make a plan. The LCD interface is easy enough, but I still like to have something on paper to refer to:

schematic12

The next step is to breadboard it – to make sure it works. However I did solder in the wires to the LCD at this stage:

lcdwiressmall

And after assembling the circuit, a brief test:

testingsm

Success. The demonstration sketch is the example provided with the Arduino IDE, modified for a 20×04 LCD. During the test above, I used an external 5 V power supply for the breadboard. Remember to connect the ground line from the Arduino to the ground line of your breadboard, otherwise it will not work. At this point I was wondering how much current the LCD used by itself. The data sheet claimed it was five milliamps… I think not. Mr Multimeter had a different opinion:

ammetersm

Now it was time to finish the soldering work. Instead of trying to jam all the wires together along the digital pins, I used some wire jumpers to spread out the landing points for the wires from the LCD:

solder1s1

Furthermore, I decided to install a power LED and 560 ohm resistor – you can never have too many LEDs. 🙂 The rear of the protoshield was also quite neat, dollops of solder easily bridged pads when required. Then after a visual inspection it was time to solder in the header pins. The easiest way to do this is to use an existing shield:

solder2s

After soldering in the pins, the first attempt of using the display was unsuccessful. I had confused a couple of wires, but some reprogramming of the sketch fixed that. (It was Saturday night and my eyes were tired). But once the error had been fixed – success!

worldclocksm

If this shield/display needed a name, I would call it the Dog’s breakfast. Now, hardware is only half of the solution – there are one or two things to take into account when writing your sketch. Also, when using .setCursor(x,y); to position the cursor, the top left position on the LCD is 0,0; and the bottom right is 19,3. For example, the image below was created by:

abcdsm

Now to make something slightly more useful to take advantage of the screen area – another clock (I like clocks) using my DS1307 real time clock shield. Here is the sketch, (doesn’t allow for DST):

… and an action shot:

worldclocksm

So there you have it. Another way to use an LCD with an Arduino, and show how you can do things yourself. High resolution photos are available from 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, HD44780, LCD, projects, tronixstuff, tutorialComments (3)

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)

Part Review – Freetronics TwentyTen “Duemiladieci”

This board has now been superseded by the Freetronics Eleven, however I’ve left the review here so you can see the evolution of the product.

Hello readers

Today we are going to examine the Freetronics “2010” (Duemiladieci in Italian). This is a 100% Arduino Duemilanove-compatible board with some very neat enhancements. It was conceived by two Arduino experts here in Australia, Jon Oxer (co-author of the fascinating book “Practical Arduino“) and Marc Alexander. These two gentleman have formed Freetronics to help people build the projects detailed in the Practical Arduino book, assist people in releasing their hardware designs and generally help accelerate the open-source hardware movement. But for now, back to the 2010. First of all, let’s have a look:

bothsmall

At first glance you may think “oh, just another Arduino clone”. Not so, however it is 100% compatible with the Arduino Duemilanove, so you can use the 2010 without any modification. Nevertheless upon closer inspection there are several small and large differences. The first thing to notice is the prototyping area. By doing some clever PCB routing, the designers have made space for a small but handy area for you to add your own circuitry. Here is a close up look:

protofrontsmall

 

protorearsmall

Furthermore the corners have been rounded off, a small but thoughtful modification. The designers have also made the effort to label everything clearly, including the voltage and socket polarity for DC input, very handy for the beginner. And to make life easier, those large copper pads on the rear are for the 5V power and GND, so voltage supply is taken care of for you.

For an example of the prototype area use, check out my DS1307 real-time clock modification! It is obvious that this board has been designed by people who use the Arduino system and not some knock-off manufacturer from eBay. The next visible differences are around the USB socket:

usbx3small

Those four holes are the X3 programming pads, much easier to use than the solder pads on the original Duemilanove. The purpose of these is to allow you to use your 2010 board as an AVR programmer, in order to program the bootloader into the microcontroller. Speaking of which, this is the ATmega328, identical to the Duemilanove’s chip. Next to the X3 pads is a mini-USB socket. In my case I love it, as when making my own shields I often need all the under-shield space I can use. For example:

clearancesmall

And don’t worry about not having the correct USB cable, as one is supplied with the 2010. Subjectively, being one metre long, it could be longer. But you cannot please everyone!

usbcablesmall

Also note that the 2010 board has another mounting hole just behind the DC power socket, which increases stability if used in a more permanent situation. Moving around to the tail end of the 2010, the four LEDs have been placed here – allowing them to stay visible even with shields on top:

ledssmall

The power LED is a nice blue colour as well, TX is yellow, RX is green, and D13 is red. The circuitry for the D13 LED has been modified slightly, it will not come on when digital pin 13 is used as an input. Otherwise, everything else is in the correct, identical position to the Arduino Duemilanove. So all your shields will work, the ICSP (in circuit serial programmer) pins are in the same spot, and the pin current ratings and board input voltage range is identical. The complete specifications can be found here: 2010.pdf. Another TwentyTen user has even over-clocked their board to 22 MHz. Amazing.

In conclusion, this is a board that is faithful to the Arduino design and improves on it. After using this board over the last ten days I can happily say it has worked flawlessly and all my sketches and shields have been compatible with the 2010. If you need another Duemilanove board, I can honestly recommend this one as a product of choice.  And if you made it this far – check out my new book “Arduino Workshop” from No Starch Press.

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

Posted in arduino, freetronics, microcontrollers, part reviewComments (2)

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)

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)

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: