Electronic components – the Resistor
Hello readers
Today we continue with the series of articles on basic electronics with this introductory article about the resistor.
With regards to this article, it is only concerned with direct current (DC) circuits.
What is a resistor? It is a component that can resist or limit the flow of current. Apart from resistors, other electronic components also exhibit an amount of resistance, however the precise amount can vary. The unit of measure of resistance is the Ohm (Ω), and named after the clever German physicist Georg Simon Ohm. He discovered that there was a relationship between voltage (the amount force that would drive a current between two points), current (the rate of flow of an electric charge) and resistance (the measure of opposition to a current) – what we know as Ohm’s law – which states that the current between two points in a conductor is directly proportional to the potential difference (voltage) between the two points, and inversely proportional to the resistance between them.
Or, current = voltage / resistance. You should remember that formula, it can be useful now and again.
But I digress.
There are many types of resistors, each with a different application – but all with the same purpose. Let’s have a look at some now…
Fixed-value leaded resistors
These are the most common type that you will come across. The larger they are, the great amount of watts (the amount of power dissipated by the resistance) they can handle. More common varieties can vary from 0.125 watt to 5 watts. For example, here is a 0.125W resistor, the length of the body is 3.25 mm.:
The body colour of these smaller resistors usually indicates the type of resistor. For example, those with a beige body are carbon resistors. They are usually the cheapest, and have a tolerance of 5%. This means that the indicated value can vary 5% either way – so if your resistor read 100 ohms, the actual value could be between 95 and 105 ohms. Resistors with a blue-ish body are metal-film resistors. They are usually a little bit more expensive, but have a 1% tolerance. Unless you are really trying to save a few cents, use metal-films. Another example is this one watt resistor:
They are much larger, this example is 25mm long and 8mm in thickness. The size of a resistor is generally proportional to its power handling ability.
Do you see the coloured bands around the resistor? They are colour codes, a way of indicating the resistance and tolerance values. And for colour-challenged electronics enthusiasts, a royal PITA. Resistor values can vary, from zero ohms (technically not a resistor… but they do exist for a good reason) up to thousands of millions (giga-) of ohms.
Let’s learn how to read the resistor colour codes. First of all, have a look at this chart (click to enlarge):
Some resistors will have four bands, some will have five. From personal experience, new resistors are generally five band now. So you just match up the first three bands from left to right, then the fourth band is your multiplier, and the last band is the tolerance. For example, the three resistors below are labelled as 560 ohm resistors:
So the bands are: green, blue, black, black, tolerance – 5, 6, 0 = 560, then 1 for multipler = 560 ohms. The carbon-film resistor (top) has a gold tolerance band – 5%, the others being metal film are brown for 1%. This is why it is much easier to have a nice auto-ranging multimeter.
Now if you need a resistor that can handle more than one watt, you move into ceramic territory. Thankfully these are large enough to have their values printed on them. For example:
There are literally scores of varieties of resistors in this physical category. If you don’t have the time or penchant to visit an electronics store, browse around online catalogues with images such as Digikey, Farnell/Newark (USA), Mouser, etc.
Surface-mount resistors
These are the becoming the norm as technology marches on. Even electronics hobbyists are starting to work with them. They consist of two metal ends which make contact with the circuit board, and a middle section which determines the resistance. They are tiny! The smallest being 0.6 x 0.3 mm in size. The smaller sizes may not have markings, so you need to carefully keep track of them.
As an aside, here is a interesting article on how to solder SMD parts at home. Moving on…
Resistor Arrays
You may find yourself in the situation where you need multiple values of the same resistor in a row, for example to limit current to a bank of LEDs or an LED display module. This is where a resistor array can be convenient. You can usually find arrays with between four and sixteen resistors in a variety of casings which speeds up prototyping greatly – however they do cost more than the individual resistors. For example: (hover over image for description)
Variable resistors
As expected there are many types of variable resistors, from the tiny to the large. Just like fixed-value resistors you need to ensure the power-handling (watts value) is sufficient for your project.
Variable resistors normally consist of a surface track that has resistive properties, and a tiny arm or contact that moves along the track. There are three terminals, one at each end of the track, and one to the arm or wiper. You would normally use the wiper contact and one of the others, depending on which way you want the variable resistor to operate (either increasing or decreasing in resistance). For example:
So as the wiper moves clockwise, the resistance increases…
Starting with the small – a variety of trimpots, used more for refining settings and not general everyday user input. Here is a small range of PCB-mount trimpots:
The two on the left are not sealed, exposed to dust and other impurities that can interfere with them. The two on the right are enclosed, and have a smoother feel when adjusting, and are generally preferable. These trimpots are single-turn, which can make getting finite adjustments in high-value resistances rather difficult. However you can purchase multi-turn trimpots allowing you greater detail in adjustment. Trimpots are usually labelled very well, depending on the manufacturer. For example, the black one above is 10k ohm, easy. Some will have a numerically coded version. Such as the one on the right. It is labelled 501, which means 50 ohms with 1 zero after it, so it is 500 ohms. Another example is 254, that is 25 with four zeros, i.e. 250000 ohms or 25 kilo ohm.
Next up are potentiometers – the garden variety variable resistor.
Apart form the resistance and wattage value, there are two major types to choose from: linear and logarithmic. The resistance of linear ‘pots’ is equally proportional to the angle of adjustment. That is, if you turn it half-way, its value is (around) 50% of the total resistance. Ideal for adjusting voltage, brightness, etc. Logarithmic are usually for volume controls. Here is a very crude example of the logarithmic VR’s resistance value relative to wiper position:
When identifying your variable resistor, units marked with ‘A’ next to the value are logarithmic, and ‘B’ are linear. For example, B10k is a 10 kilo ohm linear potentiometer. These types are also available as doubles, so you can adjust two resistances at the same time – ideal for stereo volume controls. If you are going to build a project with these and mount them into a case, be sure to check that the knobs you want to use match the shaft diameter of the potentiometer before you finalise your design.
Light-dependent resistors
These can be a lot of fun. In total darkness their resistance value is quite high, around 1 mega ohm, but in normal light drops to around 17 kilo ohm (check your data sheet). They are quite small, the head being around 8mm in diameter.
Great for determing day or night time, logging sunrise and sunset durations, or making something that buzzes only in the dark like a cricket.
Digital potentiometers
Imagine a tiny integrated circuit that contained hundreds of resistors in series, and could have the resistance selected by serial digital control. These are usually classified by the total resistance, the number of potentiometers in the chip, the number of divisions of the total resistance offered, and the volatility of the wiper. That is, when the power is turned off, does it remember where the wiper was upon reboot, or reset to a default position. For example, Maxim IC have a range of these here.
Thermistors
Think of a thermistor as a resistor that changes its resistance relative to the ambient temperature. Here is a thermistor as found in the Electronic Bricks:
And the circuit symbol:
There are positive and negative thermistors, which increase or decrease their resistance relative to the temperature. Within the scope of this website, thermistors are not an idea solution to measure temperature with our microcontrollers, it is easier to use something like an Analog Devices TMP36. However, in general analogue situations thermistors are used widely.
Mathematics of resistors
Working with resistors is easy, however some planning is required. One of the most popular uses is to reduce current to protect another component. For example, an LED. Say you have an LED that has a forward voltage of 2 volts, draws 20 mA of current, and you have a 5V supply. What resistor value will you use?
First of all, note down what we know: Vs (supply voltage) = 5V, Vl (LED voltage) = 2V, Il (LED current = 0.02A). Using Ohm’s law (voltage = current x resistance) we can rearrange it so:
resistance = voltage / current
So, resistance = (5-2)/0.02 = 150 ohms.
So in the circuit above, R1 would be 150 ohms
Resistors in series
If you have resistors in series, the total resistance is just the sum of the individual values. So R = R1 + R2 + R3 …Rx
Resistors in parallel
Using resistors in parallel is a little trickier. You might do this to share the power across several resistors, or to make a value that you can’t have with a single resistor.
Voltage division with resistors
If you cannot reduce your voltage with a zener diode, another method is voltage division with resistors. Simple, yet effective.
Always check that the resistors you are using are of a suitable power handling type. Remember that W = V x A (power in watts = volts x current in amps)!
Update – “The resistor – part two” has now been published, with more information on how resistors divide and control current, and much more. Please visit here.
Well that wraps up my introduction to resistors. As always, thank you for reading and I look forward to your comments and so on. Please subscribe using one of the methods at the top-right of this web page to receive updates on new posts. Or join our new Google Group.
Otherwise, have fun and make something!
Some information for this post is from: historical info from Wikipedia; various technical information from books by Forrest Mims III, “Electronics Demystified” by Stan Gibilisco; ceramic, array, LDR and SMD resistor photos from Farnell Australia.
Let’s make an Arduino real time clock shield
[Updated 15/03/2013]
Today we are going to make a real time clock Arduino shield. Doing so will give you a simple way of adding … real time capability to your projects such as time, date, alarms and so on. We will use the inexpensive Maxim DS1307 real-time clock IC.
First of all, we need create our circuit diagram. Thankfully the Maxim DS1307 data sheet [pdf] has this basics laid out on page one. From examining a DS1307 board used in the past, the pull-up resistors used were 10k ohm metal films, so I’m sticking with that value. The crystal to use is 32.768 kHz, and thankfully Maxim have written about that as well in their application notes [pdf], even specifying which model to use. Phew!
So here is the circuit diagram we will follow (click on it to enlarge):
Which gives us the following shopping list:
- One arduino protoshield pack. I like the yellow ones from Freetronics
- X1 – 32.768 kHz crystal – Citizen America part CFS206. You should probably order a few of these, I broke my first one very quickly…
- IC1 – Maxim DS1307 real time clock IC
- 8-pin IC socket
- CR2032 3v battery
- CR2032 PCB mount socket
- R1~R3 – 10k ohm metal film resistors
- C1 – 0.1 uF ceramic capacitor
And here are our parts, ready for action:
The first thing to do is create the circuit on a solderless breadboard. It is much easier to troubleshoot possible issues before soldering the circuit together. Here is the messy test:
Messy or not, it worked. You can use the following sketch to test the circuit is working.
The next step is to consider the component placement and wiring for the protoshield. Please note that my board will most likely be different to yours, so please follow the schematic and not my board positioning. Try not to rush this step, and triple-check your layout against the schematic. As my protoshield has a green and red LED as well, I have wired the square-wave output to the green LED. You can never have too many blinking lights…
At this point I celebrated the union of tea and a biscuit. After returning to the desk, I checked the layout once more, and planned the solder bridges. All set – it was time to solder up. If you have the battery in the holder for some reason, you should remove it now, as they do not like getting warm. Furthermore, that crystal is very fragile, so please solder it in quickly.
And here we are – all soldering done except for the header sockets. At this point I used the continuity function of the multimeter to check the solder joints and make sure nothing was wrong with the circuit.
Final checks passed, so on with the headers. To make this easier, I stick some header pins in the sockets, then place the whole lot in a solderless breadboard to keep it straight. Well, it works for me:
Just a side note – always make sure you have enough consumables, the right tools, etc., before you start a project. This is how much solder I had left afterwards…
Moving on … in with the battery and the DS1307 – we’re done!
It is now time for the moment of truth – to insert the USB cable and re-run the sketch… and it worked! The blinking LED was too bright for me, so I de-soldered the wire. If you are making a shield, congratulations to you if yours worked as well. Note that if you are using this shield, you cannot use analog pins 4 and 5 – they are being used as the I2C bus.
So there we have it. Another useful shield, and proof that the Arduino system makes learning easy and fun. High resolution photos are available on flickr.
In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, 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.
Electronic components – the Diode
Hello readers
Although my posts have generally been about microcontrollers, kits and related items, I have been rather lax in writing about electronics in general, and that magical world of wonder known as analogue electronics… i.e “Before Arduino”
So let’s go back to some of the basics. Starting with the diode
What is a diode? It is an electronic component that allows current to only flow in one direction. Before the advent of semiconductors, vacuum tube diodes were used. Thankfully no more…
A diode is comprised of two types of semiconductor crystal (usually made from silicon or germanium) that are highly refined then doped with an impurity. Depending on the impurity, the crystal can either be called an “N-type” or “P-type”. When you put an N-doped region next to a P-doped region, a diode or PN junction is formed. In our diodes, the P-region is called the anode, and the N-region is called the cathode. As you can imagine, these properties are useful, allowing current to flow only in one direction.
The basic symbol for a diode in a circuit diagram or schematic is this:
So in a circuit, the current only flows in one direction, for example:
When a diode is connected in this way, it is said to be forward-biased, that is the anode is connected to a higher voltage than the cathode. If the diode was reversed, with the cathode connected to the higher voltage, it would not allow current to flow, and therefore would break the circuit. A forward-biased diode is considered to be a closed switch, as the voltage does not drop as the current passes through the diode. However that is assuming the diode is perfect. And like many other things in life, it is not perfect.
All diodes are not perfect, and have what is called a forward voltage drop, this is the amount by which the voltage decreases as the current passes through the diode from anode to cathode. For silicon diodes, this is ~0.7 volts; for germanium diodes ~0.3 volts.
Diodes are also manufactured to handle a certain amount of power. Recall that:
power (watts) = current (amps) x voltage (volts)
As the voltage drop with our normal diode is 0.7V, the power dissipated by the diode can be calculated by simply multiplying the current by 0.7.
For example, if we have a 1 watt diode, how much current can it handle?
1 = current x 0.7; current = 1/0.7
Current = 1.42
So the 1 watt diode can theoretically handle 1.42 amps of current.
What happens if you use a diode the other way, that is attempt to allow current to flow from the cathode through to the anode. Ideally nothing will happen – to a point. Diodes have a breakdown voltage, when a reverse-biased (backwards) diode starts to allow current to flow through it. The breakdown voltage of each type of diode is different, it depends on the manufacturer. The best way to find out what the breakdown voltage of your diode is to check the data sheet. For example, a popular diode is the 1N4001. From page two of the data sheet (pdf), comes the following table:
So for the 1N4001 diode, the breakdown voltage is 50V. Peak repetitive means that the diode can sustain doing this more than once. Excessive voltage will not usually destroy a diode. Excessive current will destroy a diode. This is interesting, as you can use a diode as a voltage regulator, provided that you don’t exceed the maximum current it can handle. Refresh your memory about voltage division with resistors. The disadvantage of using two resistors is that it can be difficult to purchase precise values.
So let’s use a zener diode instead. They are manufactured with a much more precise (and lower) voltage; and handle less power. Zener diodes have a slightly different symbol:
Zener diodes will usually (hopefully) have their breakdown voltage within their part number. For example, an NXP 4.7V zener diode’s part number is: BZX79-B4V7. The 4V7 is the breakdown voltage, with a V for the decimal point. It can handle 500 mW, but this is not obvious – once again, you will need the data sheet (pdf). Below is a photo of a typical zener diode. It is very small, the grid paper beneath it is 5mm square. The ring or dark band around one end of the diode always indicates the cathode end.
And now for an example. We have a tiny Zilog ePIR that requires a nice smooth 3.3v DC, and only draws 10mA, however the power rail on our prototype is 5V. This is a job for a 3.3V zener diode. Here is our schematic:
We need to calculate the appropriate resistance to limit the current through our zener diode. We are using a Fairchild BZX55C3v3 (data sheet pdf). Maximum power is 500mW or 1 watt. To calculate the value of the resistor, we will need the maximum current for the diode, calculated by
current = power / voltage
current = 0.5 watts / 3.3 volts
current = 0.150 A or 150 mA.
Using Ohm’s law, resistance = voltage /current
resistance = 1.7 volts / .15 A
resistance = 11.333333 = 12 ohms
So we would use a nice metal film 1% tolerance 12 ohm resistor, rated at 500 mW. Easy, 1.2 cents from RS or element-14.
Another type of diode is the signal diode. They handle much less current, usually around 100 mA, but are more suited for high-frequency signals, or semiconductor protection.Signal diodes can have a high breakdown voltage, but low power handling ability. A very popular signal diode used is the 1N4148 (data sheet), an example of which is below:
For example, a signal diode may be places across the coil of a relay that is being controlled by a transistor – as it allows the current produced by the change in magnetic field when the coil is deactivated to head through the coil instead of the transistor. For example, when using an Arduino to control a relay coil:
Our next diode type is the germanium diode. They have a very small voltage drop of 0.2V, and are mostly used in crystal radio sets. They are very fragile, but are ideal for putting across a radio wave signal to convert it from AC to DC, which can then be amplified. If you are interested, here are some guides to making a crystal radio.
Another type of diode is the Schottky diode (named after the German physicist Walter Schottky). The symbol for a schottky diode is this:
There are two main differences between a schottky diode and a normal diode. One – a schottky diode does not have a discernible recovery time between conducting and not conducting a current. For example, a normal diode may take around a few hundred nanoseconds; whereas a schottky does not. This makes them useful in situations that involve very very high speed switching of current (for example, DC-DC converters such as Limor Fried’s mintyboost). Two – a schottky diode has a smaller forward voltage, a typical example (data sheet) is 0.55v.
Finally we come to rectifier diodes. Their main feature is the ability to handle large amounts of current, from 1 amp upwards; and higher breakdown voltages. For example the 1N4001 (data sheet) diode is 50V at 1 amp; the 1N5401 (data sheet) is 100V at 3 amps. The main purpose of these diodes is to protect against incorrect polarity from power supplies, and to convert AC to DC. For example, if you were designing a childrens’ toy that used a 9V battery, you would use reverse-bias a rectifier diode between 9V and GND in case the child forced the battery in the wrong way.
But how can rectifier diodes convert AC to DC power? Very easily – through the use of a bridge rectifier. A bridge rectifier is basically four rectifier diodes connected together, for example:
When the AC power is between 0 and maximum wave, the positive DC rail is fed by the path: 1,2,3,4; the negative DC rail is 8,7,6,5. When the AC power is between 0 and minimum wave, the positive DC rail is fed by the path: 5,6,3,4; the negative DC rail is: 8,7,2,1.
Bridge rectifiers come in various shapes and sizes, for example DIP packaging for 1A 100V models:
right through to 300A 1600V models…
Last but not least is the light emitting diode (LED). An LED is a special kind of diode, when it is forward-biased and a current applied, it releases energy in the form of light instead of heat. Here is the common schematic symbol for an LED:
When using an LED it is critical to ensure you have the correct voltage, otherwise your LED will overheat, burn your fingers when you touch it then eventually break. Always consult your data sheet. Calculating the correct voltage is quite simple. Using a bog-standard 5mm RED LED as an example (data sheet), you can use the following formula:
R = (Vs-Vled) / A
where:
- R = value of resistor to use in ohms
- Vs is your supply voltage in volts DS
- Vled is the forward voltage of the LED at the recommended current
- A is the recommended operation current of the LED
So for our example, we will use a 9V battery, and the LED from the data sheet above, Vled is 2V and A is 20 mA or 0.02 A
That gives us R = (9-2)/0.02 = 7/0.02 = 350 ohms.
Therefore, place a 350 ohm resistor between the positive of the battery and the anode of the LED. The most popular value of resistor to use would be a 390 ohm, 1/4 watt.
You can find LEDs in many different colours, and also units with two or more LEDs in the one housing, example red, green and blue. Some LEDs also create light in non-visible wavelengths, such as infra-red – these are used in remote-control applications and night-vision equipment. However if you are reading this, you would know by now where to find LEDs.
Well that wraps up my introduction to diodes. As always, thank you for reading and I look forward to your comments and so on. Please subscribe using one of the methods at the top-right of this web page to receive updates on new posts. Or join our new Google Group.
Otherwise, have fun and make something!
Some information for this post came from various books by Forrest Mims III; ”All-new Electronics Self-Teaching Guide” by Harry Kybett and Earl Boysen; and data sheets by Fairchild, NXP, ON Semiconductor and Vishay; images of bridge rectifiers from Farnell Australia, LED and schottky diode symbols from electricalwhat.com.
Part Review – Freetronics TwentyTen “Duemiladieci”
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. Jon and Marc were recently interviewed about Freetronics and the 2010 by Marcus Schappi, a copy of which can be viewed here.
But for now, back to the 2010. First of all, let’s have a look:
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:
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:
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:
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!
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.
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.
It is available directly from Freetronics, or other retailers including Little Bird Electronics.
High resolution photos are available on flickr.
As always, thank you for reading and I look forward to your comments and so on. Please subscribe using one of the methods at the top-right of this web page to receive updates on new posts. Or join our new Google Group.
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.
Welcome back fellow arduidans!
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 0×10 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:
// Example 8.1
int character = 0; // for incoming serial data
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available() > 0)
{
character = Serial.read();
{
Serial.write(character);
}
}
}
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:
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…
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.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, 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.
Part review – Sparkfun/LBE Thumb Joystick
Hello readers
Today we examine an inexpensive yet fascinating little input device – the thumb joystick. Many people would recognise this as similar to the joystick in various types of gaming consoles, and they would be right. Let’s have a look:
In the image above the joystick has been soldered into the matching breakout board. Unless you are making your own PCBs, you will want the breakout board:
The joystick consists of two 10k variable resistors, spring-loaded with centre return; also a SPST button that is activated by pushing down on the joystick.
In order to use this joystick, we need an idea of the values that it can return. I have done this in three ways:
First of all, I connected a multimeter and measured the resistance of each axis. For the vertical axis, dead centre was 3.77k ohms, maximum up was 4.7k, with a maximum of 5.9k between centre and maximum – very odd. The vertical minimum was 83 ohms. For the horizontal, dead centre was around 3.73k ohms, full left was 4.78k, via 5.38k; full right was 180 ohms without any odd high values in between. However, those values didn’t feel right.
Secondly, I have recorded a visual representation of the horizontal and vertical axes’ effect on the supply voltage, using my little oscilloscope. With regards to the following two video clips, the supply voltage is 5V; the ‘scope display is set to 1V/division, with 0V at the bottom of the screen.
The horizontal axis:
and the vertical axis:
Finally, I connected the horizontal and vertical output to analog inputs on my Arduino, and used analogRead() to see how the joystick returned analogRead() values. The following video clip demonstrates this using an LCD to display the values. Furthermore, here is the sketch used for the following demonstration: demo sketch.pdf
It would seem that there is a lot of ‘dead area’… postions where there is no change in reading, where one would assume there to be a change. Again, this can be programmed out in your sketch by a little calibration and measurement.
Now we know what values it returns, we can start to understand how to control things. When it comes to use the joystick in your own projects, it would pay to recreate a measurement circuit and note down the values your joystick returns; in order to be able to calibrate your software to use the joystick appropriately you may need to compensate for the hardware irregularities of the joystick.
Overall however, it is an interesting and easy product to integrate into your projects. This post today is just an introduction, later on the joysticks will be used in other projects and so on. High resolution photos are available on flickr. And if you enjoy my tutorials, or want to introduce someone else to the interesting world of Arduino – check out my new book “Arduino Workshop” from No Starch Press.
In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, 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.
Let’s make an Arduino LCD shield
In this short tutorial we make an Arduino LCD shield.
Updated 18/03/2013
Today we are going to make an Arduino shield with an LCD module. More often than not I have needed to use an LCD shield in one of my projects, or with the Arduino tutorials. Naturally you can buy a pre-made one, however doing your own is always fun and nice way to pass an afternoon. Before we start, let me say this: “to fail to plan is to plan to fail”. That saying is very appropriate when it comes to making your own shields.
The first step is to gather all of the parts you will need. In this case:
- an LCD module (backlit if possible, but I’m being cheap and using a non-backlit module) that is HD44780-compatible
- a 10k linear trimpot, used to adjust the LCD contrast
- a blank protoshield that matches your Arduino board
- various header pins required to solder into the shield (they should be included with your protoshield)
- plenty of paper to draw on
For example:
Next, test your parts to ensure everything works. So, draw a schematic so you have something to follow:
And then build the circuit on a solderless breadboard, so you can iron out all the hardware bugs before permanently soldering into the shield. If you have a backlit LCD, pins 15 and 16 are also used, 15 for backlight supply voltage (check your data sheet!) and 16 for backlight ground:
Once connected, test the shield with a simple sketch – for example the “HelloWorld” example in the Arduino IDE. Make sure you have the library initialization line:
LiquidCrystal lcd();
filled with the appropriate parameters. If you’re not sure about this, visit the LCD display tutorial in my Arduino tutorials.
Now to make the transition from temporary to permanent. Place your components onto the protoshield, and get a feel for how they can sit together. Whilst doing this, take into account that you will have to solder some jumper wires between the various pads and the digital pin contacts and the 5V strip at the top row, as well as the GND strip on the bottom row. You may find that you have to solder jumper wires on the bottom of the shield – that’s fine, but you need to ensure that they won’t interfere with the surface of your Arduino board as well.
Furthermore, some protoshields have extra functions already added to the board. For example, the shield I am using has two LEDs and a switch, so I will need to consider wiring them up as well – if something is there, you shouldn’t waste the opportunity to not use them.
If your shield has a solder mask on the rear, a great way to plan your wiring is to just draw them out with a whiteboard marker:
Remember to solder these wires in *before* the LCD … otherwise you will be in a whole world of pain. The LCD should be soldered in second-last, as it is the most difficult thing to desolder if you have made any mistakes. The last items to solder will be the header pins. So let’s get soldering…
After every solder joint, I pushed in the LCD module – in order to check my placement. You can never check too many times, even doing so I made a small mistake. Having a magnifying glass handy is also a great idea:
Now just to soldier on, soldering one pad at a time, then checking the joint and its relationship with where it should be on the board. Be very careful when applying solder to the pads, they can act as a “drain” and let lots of solder flow into the other side. If this happens you will spend some time trying to remove that excess solder – a solder sucker and some solder wick is useful for this.
Finally all the wires and pads were connected, and I checked the map once more. Soldering in the LCD was the easiest part – but it is always the most difficult to remove – so triple check your work before installing the display. Now it was time to sit in the header sockets, and test fit the shield into my arduino board. This is done to make sure there is sufficient space between the wires on the bottom of our shield and the top of the arduino:
Even though you wouldn’t normally put a shield on top of this shield, I used the header sockets to allow access to all of the arduino pins just in case. Soldering the sockets was easy, I used blu-tack to hold them into place. Crude but effective.
And we’re finished. Soldering is not the best of my skills, so I checked continuity between the pins on the LCD and where they were supposed to go, and also electrically checked for bridges between all the soldered pins to check for shorts. A multimeter with a continuity buzzer makes this easy. Naturally I had a short between LCD pin 14 and 13, but some solder wick helped me fix that.
So electrically it was correct… time to see if it actually worked! At this point it is a good idea to clear up the workspace, switch off the soldering iron, put it somewhere safe to cool down, then wash your hands thoroughly.
Here are some photos of the finished product on my arduino board:
As we’re using a Freetronics protoshield with onboard LEDs, the only thing to do was alter the demonstration sketch to take account for the pin placements, and insert some code to blink the LEDs. I never need an excuse to make a video clip, so here is the result:
So there you have it. With a little planning and care, you too can make your own Arduino shield. An LCD shield would be useful for everyone, as they are great for displaying data and requesting input, yet quite fiddly to use with a solderless breadboard. High resolution photos are available on flickr.
In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, 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.
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:
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:
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.
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:
switch (zz) {
case 10:
//do something when variable zz equals 10
break;
case 20:
//do something when variable zz equals 20
break;
case 30:
// do something when variable equals 30
break;
default:
// if nothing else matches, do the default
// default is optional
}
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).
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:
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: (click on image to enlarge)
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 0×68 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:
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:
/*
DS1307 Square-wave machine
Used to demonstrate the four different
square-wave outputs from Maxim DS1307
See page nine of data sheet for more information
http://tronixstuff.wordpress.com
CC by-nc-sa v3.0
*/
#include "Wire.h"
#define DS1307_I2C_ADDRESS 0x68 // each I2C object has a unique bus address, the DS1307 is 0x68
void setup()
{
Wire.begin();
}
void sqw1() // set to 1Hz
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x10); // sends 0x10 (hex) 00010000 (binary)
Wire.endTransmission();
}
void sqw2() // set to 4.096 kHz
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x11); // sends 0x11 (hex) 00010001 (binary)
Wire.endTransmission();
}
void sqw3() // set to 8.192 kHz
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x12); // sends 0x12 (hex) 00010010 (binary)
Wire.endTransmission();
}
void sqw4() // set to 32.768 kHz (the crystal frequency)
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x13); // sends 0x13 (hex) 00010011 (binary)
Wire.endTransmission();
}
void sqwOff()
// turns the SQW off
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0x07); // move pointer to SQW address
Wire.write(0x00); // turns the SQW pin off
Wire.endTransmission();
}
void loop()
{
sqw1();
delay(5000);
sqw2();
delay(5000);
sqw3();
delay(5000);
sqw4();
delay(5000);
sqwOff();
delay(5000);
}
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.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, 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.
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.
void displaynumber(int rawnumber, int cycles)
// takes an integer and displays it on our 4-digit LED display module and HOLDS it on the display for 'cycles' number of cycles
{
for (int q=1; q<=cycles; q++)
{
if (rawnumber>=0 && rawnumber<10)
{
onedigitnumber(rawnumber);
}
else if (rawnumber>=10 && rawnumber<100)
{
twodigitnumber(rawnumber);
}
else if (rawnumber>=100 && rawnumber<1000)
{
threedigitnumber(rawnumber);
}
else if (rawnumber>=1000)
{
fourdigitnumber(rawnumber);
}
}
}
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.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, 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.
We now have a Google Group!
Hello readers
I would like to announce the opening of our own tronixstuff discussion email list via Google Groups: http://groups.google.com/group/tronixstuff
Through this group we can discuss posts, projects, products and anything else mentioned on the tronixstuff or related websites. For the time being it will be moderated until we get going and see what the level of conversation is like. However, please feel free to ask questions, offer suggestions, or make constructive criticism about anything in the tronixstuff world.
It is also meant for support with any of the Arduino tutorials or products mentioned in the blog. I will do my best to help you, so don’t be afraid to ask!
However it is not for spam, discrimination, attacking others, or blatantly selling things.
So sign up now!













































































