## Arduino Tutorials – Chapter 22 – the AREF pin

Learn how to measure smaller voltages with greater accuracy using your Arduino.

This is chapter twenty-two of our huge Arduino tutorial seriesUpdated 12/12/2013

In this chapter we’ll look at how you can measure smaller voltages with greater accuracy using the analogue input pins on your Arduino or compatible board in conjunction with the AREF pin. However first we’ll do some revision to get you up to speed. Please read this post entirely before working with AREF the first time.

Revision

You may recall from the first few chapters in our tutorial series that we used the analogRead() function to measure the voltage of an electrical current from sensors and so on using one of the analogue input pins. The value returned from analogRead() would be between zero an 1023, with zero representing zero volts and 1023 representing the operating voltage of the Arduino board in use.

And when we say the operating voltage – this is the voltage available to the Arduino after the power supply circuitry. For example, if you have a typical Arduino Uno board and run it from the USB socket – sure, there is 5V available to the board from the USB socket on your computer or hub – but the voltage is reduced slightly as the current winds around the circuit to the microcontroller – or the USB source just isn’t up to scratch.

This can easily be demonstrated by connecting an Arduino Uno to USB and putting a multimeter set to measure voltage across the 5V and GND pins. Some boards will return as low as 4.8 V, some higher but still below 5V. So if you’re gunning for accuracy, power your board from an external power supply via the DC socket or Vin pin – such as 9V DC. Then after that goes through the power regulator circuit you’ll have a nice 5V, for example:

This is important as the accuracy of any analogRead() values will be affected by not having a true 5 V. If you don’t have any option, you can use some maths in your sketch to compensate for the drop in voltage. For example, if your voltage is 4.8V – the analogRead() range of 0~1023 will relate to 0~4.8V and not 0~5V. This may sound trivial, however if you’re using a sensor that returns a value as a voltage (e.g. the TMP36 temperature sensor) – the calculated value will be wrong. So in the interests of accuracy, use an external power supply.

Why does analogRead() return a value between 0 and 1023?

This is due to the resolution of the ADC. The resolution (for this article) is the degree to which something can be represented numerically. The higher the resolution, the greater accuracy with which something can be represented. We measure resolution in the terms of the number of bits of resolution.

For example, a 1-bit resolution would only allow two (two to the power of one) values – zero and one. A 2-bit resolution would allow four (two to the power of two) values – zero, one, two and three. If we tried to measure  a five volt range with a two-bit resolution, and the measured voltage was four volts, our ADC would return a numerical value of 3 – as four volts falls between 3.75 and 5V. It is easier to imagine this with the following image:

So with our example ADC with 2-bit resolution, it can only represent the voltage with four possible resulting values. If the input voltage falls between 0 and 1.25, the ADC returns numerical 0; if the voltage falls between 1.25 and 2.5, the ADC returns a numerical value of 1. And so on. With our Arduino’s ADC range of 0~1023 – we have 1024 possible values – or 2 to the power of 10. So our Arduinos have an ADC with a 10-bit resolution.

So what is AREF?

To cut a long story short, when your Arduino takes an analogue reading, it compares the voltage measured at the analogue pin being used against what is known as the reference voltage. In normal analogRead use, the reference voltage is the operating voltage of the board. For the more popular Arduino boards such as the Uno, Mega, Duemilanove and Leonardo/Yún boards, the operating voltage of 5V. If you have an Arduino Due board, the operating voltage is 3.3V. If you have something else – check the Arduino product page or ask your board supplier.

So if you have a reference voltage of 5V, each unit returned by analogRead() is valued at 0.00488 V. (This is calculated by dividing 1024 into 5V). What if we want to measure voltages between 0 and 2, or 0 and 4.6? How would the ADC know what is 100% of our voltage range?

And therein lies the reason for the AREF pin. AREF means Analogue REFerence. It allows us to feed the Arduino a reference voltage from an external power supply. For example, if we want to measure voltages with a maximum range of 3.3V, we would feed a nice smooth 3.3V into the AREF pin – perhaps from a voltage regulator IC. Then the each step of the ADC would represent around 3.22 millivolts (divide 1024 into 3.3).

Note that the lowest reference voltage you can have is 1.1V. There are two forms of AREF – internal and external, so let’s check them out.

External AREF

An external AREF is where you supply an external reference voltage to the Arduino board. This can come from a regulated power supply, or if you need 3.3V you can get it from the Arduino’s 3.3V pin. If you are using an external power supply, be sure to connect the GND to the Arduino’s GND pin. Or if you’re using the Arduno’s 3.3V source – just run a jumper from the 3.3V pin to the AREF pin.

To activate the external AREF, use the following in void setup():

This sets the reference voltage to whatever you have connected to the AREF pin – which of course will have a voltage between 1.1V and the board’s operation voltage.

Very important note – when using an external voltage reference, you must set the analogue reference to EXTERNAL before using analogRead(). This will prevent you from shorting the active internal reference voltage and the AREF pin, which can damage the microcontroller on the board.

If necessary for your application, you can revert back to the board’s operating voltage for AREF (that is – back to normal) with the following:

Now to demonstrate external AREF at work. Using a 3.3V AREF, the following sketch measures the voltage from A0 and displays the percentage of total AREF and the calculated voltage:

The results of the sketch above are shown in the following video:

Internal AREF

The microcontrollers on our Arduino boards can also generate an internal reference voltage of 1.1V and we can use this for AREF work. Simply use the line:

For Arduino Mega boards, use:

in void setup() and you’re off. If you have an Arduino Mega there is also a 2.56V reference voltage available which is activated with:

Finally – before settling on the results from your AREF pin, always calibrate the readings against a known good multimeter.

Conclusion

The AREF function gives you more flexibility with measuring analogue signals. If you are interested in using specific ADC components, we have tutorials on the ADS1110 16-bit ADC and the NXP PCF 8591 8-bit A/D and D/A IC.

Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.

## Kit Review – Altronics 3 Digit Counter Module

Introduction

In this review we examine the three digit counter module kit from Tronixlabs. The purpose of this kit is to allow you to … count things. You feed it a pulse, which it counts on the rising edge of the signal. You can have it count up or down, and each kit includes three digits.

You can add more digits, in groups of three with a maximum of thirty digits. Plus it’s based on simple digital electronics (no microcontrollers here) so there’s some learning afoot as well. Designed by Graham Cattley the kit was first described in the now-defunct (thanks Graham) January 1998 issue of Electronics Australia magazine.

Assembly

The kit arrives in the typical retail fashion:

And includes the magazine article reprint along with an “electronics reference sheet” which covers many useful topics such as resistor colour codes, various formulae, PCB track widths, pinouts and more. There is also a small addendum which uses two extra (and included) diodes for input protection on the clock signal:

The counter is ideally designed to be mounted inside an enclosure of your own choosing, so everything required to build a working counter is included however that’s it:

No IC sockets, however I decided to live dangerously and not use them – the ICs are common and easily found. The PCBs have a good solder mask and silk screen:

With four PCBs (one each for a digit control and one for the displays) the best way to start was to get the common parts out of the way and fitted, such as the current-limiting resistors, links, ICs, capacitors and the display module. The supplied current-limiting resistors are for use with a 9V DC supply, however details for other values are provided in the instructions:

At this point you put one of the control boards aside, and then start fitting the other two to the display board. This involves holding the two at ninety degrees then soldering the PCB pads to the SIL pins on the back of the display board. Starting with the control board for the hundreds digit first:

… at this stage you can power the board for a quick test:

… then fit the other control board for the tens digit and repeat:

Now it’s time to work with the third control board. This one looks after the one’s column and also a few features of the board. Several functions such as display blanking, latch (freeze the display while still counting) and gate (start or stop counting) can be controlled and require resistors fitted to this board which are detailed in the instructions.

Finally, several lengths of wire (included) are soldered to this board so that they can run through the other two to carry signals such as 5V, GND, latch, reset, gate and so on:

These wires can then be pulled through and soldered to the matching pads once the last board has been soldered to the display board:

You also need to run separate wires between the carry-out and clock-in pins between the digit control boards (the curved ones between the PCBs):

For real-life use you also need some robust connections for the power, clock, reset lines, etc., however for demonstration use I just used alligator clips. Once completed a quick power-up showed the LEDs all working:

How it works

Each digit is driven by a common IC pairing – the  4029 (data sheet) is a presettable up/down counter with a BCD (binary-coded decimal) output which feeds a 4511 (data sheet) that converts the BCD signal into outputs for a 7-segment LED display. You can count at any readable speed, and I threw a 2 kHz square-wave at the counter and it didn’t miss a beat. By default the units count upwards, however by setting one pin on the board LOW you can count downwards.

Operation

Using the counters is a simple matter of connecting power, the signal to count and deciding upon display blanking and the direction of counting. Here’s a quick video of counting up, and here it is counting back down.

Conclusion

This is a neat kit that can be used to count pulses from almost anything. Although some care needs to be taken when soldering, this isn’t anything that cannot be overcome without a little patience and diligence. So if you need to count something, get one or more of these kits from Tronixlabs Australia. Full-sized images are available on flickr. And while you’re here – are you interested in Arduino? Check out my book “Arduino Workshop” from No Starch Press – also available from Tronixlabs.

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.

## Various 1 Hz Oscillator Methods

Introduction

During the fun and enjoyment of experimenting with electronics there will come a time when you need a nice 1 Hz oscillator to generate a square-wave signal to drive something in the circuit. On… off… on… off… for all sorts of things. Perhaps a metronome, to drive a TTL clock, blink some LEDs, or for more nefarious purposes. No matter what you need that magic 1 Hz for – there’s a variety of methods to generate it – some more expensive than others – and some more accurate than others.

A few of you may be thinking “pull out the Arduino” and yes, you could knock out a reasonable 1 Hz – however that’s fine for the bench, but wild overkill for embedding a project as a single purpose. So in this article we’ll run through three oscillator methods that can generate a 1 Hz signal (and other frequencies) using methods that vary in cost, accuracy and difficulty – and don’t rely on mains AC. That will be a topic for another day.

Using a 555 timer IC

You can solve this problem quite well for under a dollar with the 555, however the accuracy is going to heavily rely on having the correct values for the passive components. We’ll use the 555 in astable mode, and from a previous article here’s the circuit:

And with a 5V power supply, here’s the result:

As you can see the cycle time isn’t the best, which can be attributed to the tolerance of the resistors and capacitor C1. A method to increase the accuracy would be to add small trimpots in series with the resistors (and reduce their value accordingly by the trimpot value) – then measure the output with a frequency counter (etc). whilst adjusting the trimpots. If you’re curious about not using C2, the result of doing so introduces some noise on the rising edge, for example:

So if you’ve no other option, or have the right values for the passives – the 555 can do the job. Or get yourself a 555 and experiment with it, there’s lots of fun to be had with it.

A variety of GPS modules have a one pulse per second output (PPS) and this includes my well-worn EM406A module (as used in the Arduino tutorials):

With a little work you can turn that PPS output into a usable and incredibly accurate source of 1 Hz. As long as your GPS can receive a signal. In fact, this has been demonstrated in the April 2013 edition of Silicon Chip magazine, in their frequency counter timebase project. But I digress.

If you have an EM406A you most likely have the cable and if not, get one to save your sanity as the connector is quite non-standard. If you’re experimenting a breakout board will also be quite convenient, however you can make your own by just chopping off one end of the cable and soldering the required pins – for example:

You will need access to pins 6, 5, 2 and 1. Looking at the socket on the GPS module, they are numbered 6 to 1 from left to right. Pin 6 is the PPS output, 5 is GND, 2 is for 5V and 1 is GND. Both the GNDs need to be connected together.

Before moving forward you’re probably curious about the pulse, and want to see it. Good idea! However the PPS signal is incredibly quick and has an amplitude of about 2.85 V. If you put a DSO on the PPS and GND output, you can see the pulses as shown below:

To find the length of the pulse, we had to really zoom in to a 2 uS timebase:

Wow, that’s small. So a little external circuitry is required to convert that minuscule pulse into something more useful and friendly. We’ll increase the pulse length by using a “pulse stretcher”. To do this we make a monostable timer (“one shot”) with a 555. For around a half-second pulse we’ll use 47k0 for R1 and 10uF for C1. However this triggers on a low signal, so we first pass the PPS signal through a 74HC14 Schmitt inverter – a handy part which turns irregular signals into more sharply defined ones – and also inverts it which can then be used to trigger the monostable. Our circuit:

and here’s the result – the PPS signal is shown with the matching “stretched” signal on the DSO:

So if you’re a stickley for accuracy, or just want something different for portable or battery-powered applications, using the GPS is a relatively simple solution.

Using a Maxim DS1307/DS3232 real-time clock IC

Those of you with a microcontroller bent may have a Maxim DS1307 or DS3232. Apart from being pretty easy to use as a real-time clock, both of them have a programmable square wave output. Connection via your MCU’s I2C bus is quite easy, for example with the DS1307:

Using a DS3232 is equally as simple. We use a pre-built module with a similar schematic. Once you have either of them connected, the code is quite simple. For the DS1307 (bus address 0x68), write 0x07 then 0x11 to the I2C bus – or for the DS3232 (bus address is also 0x68) write 0x0E then 0x00. Finally, let’s see the 1 Hz on the DSO:

Certainly not the cheapest method, however it gives you an excellent level of accuracy without the GPS.

Conclusion

By no means is this list exhaustive, however hopefully it was interesting and useful. If there’s any other methods you’d like to see demonstrated, leave a comment below and we’ll see what’s possible. 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 1 hz, clocks, timebase, tronixstuff, TTL, tutorialComments (5)

## Australian Electronics Nostalgia – Talking Electronics Kits

Introduction

From 1981, Australian electrical engineer Colin Mitchell started publishing his home-grown electronics magazine “Talking Electronics”. His goal was to get people interested and learning about electronics, and more so with a focus on digital electronics. It was (and still is) a lofty goal – in which he succeeded. From a couple of rooms in his home the magazine flourished, and many projects described within were sold as kits. At one stage there were over 150 Talking Electronics kits on the market. You could find the books and kits in retail outlets such as Dick Smith Electronics, and for a short while there was a TE store in Moorabbin (Victoria). Colin and the team’s style of writing was easy to read and very understandable – but don’t take my word for it, you can download the magazines from his website (they’re near the bottom of the left column). Dave Jones recently interviewed Colin, and you can watch those for much more background information.

Over fifteen issues you could learn about blinking LEDs all the way to making your own expandable Z80 board computer, and some of the kits may still be available. Colin also published a series of tutorial books on electronics, and also single-magazine projects. And thus the subjects of our review … we came across the first of these single-issue projects from 1981 – the Mini Frequency Counter (then afterwards we have another kit):

How great is that? The PCB comes with the magazine. This is what set TE apart from the rest, and helped people learn by actually making it easy to build what was described in the magazine instead of just reading about it. For 1981 the PCB was quite good – they were silk-screened which was quite rare at the time:

And if you weren’t quite ready, the magazine also included details of a square-wave oscillator to make and a 52-page short course in digital electronics. However back to the kit…

Assembly

The kit uses common parts and I hoard CMOS ICs so building wasn’t a problem. This (original) version of the kit used LEDs instead of 7-segment displays (which were expensive at the time) so there was plenty of  careful soldering to do:

And after a while the counter started to come together. I used IC sockets just in case:

The rest was straight-forward, and before long 9 V was supplied, and we found success:

To be honest progress floundered for about an hour at this point – the display wouldn’t budge off zero. After checking the multi-vibrator output, calibrating the RC circuits and finally tracing out the circuit with a continuity tester, it turned out one of the links just wasn’t soldered in far enough – and the IC socket for the 4047 was broken So a new link and directly fitting the 4047 fixed it. You live and learn.

Operation

So – we now have a frequency counter that’s good for 100 Hz to the megahertz range, with a minimum of parts. Younger, non-microcontroller people may wonder how that is possible – so here’s the schematic:

The counter works by using a multi-vibrator using a CD4047 to generate a square-wave at 50, 500 and 5 kHz, and the three trimpots are adjusted to calibrate the output. The incoming pulses to measure are fed to the 4026 decade counter/divider ICs. Three of these operate in tandem and each divide the incoming count by ten – and display or reset by the alternating signal from the 4047. However for larger frequencies (above 900 Hz) you need to change the frequency fed to the display circuit in order to display the higher (left-most) digits of the result. A jumper wire is used to select the required level (however if you mounted the kit in a case, a knob or switch could be used).

For example, if you’re measuring 3.456 MHz you start with the jumper on H and the display reads 345 – then you switch to M to read 456 – then you switch to the L jumper and read 560, giving you 3456000 Hz. If desired, you can extend the kit with another PCB to create a 5-digit display. The counter won’t be winning any precision contests – however it has two purposes, which are fulfilled very well. It gives the reader an inexpensive piece of test equipment that works reasonably well, and a fully-documented project so the reader can understand how it works (and more).

And for the curious –  here it is in action:

[Update 20/07/2013] Siren Kit

Found another kit last week, the Talking Electronics “DIY Kit #31 – 9V siren”. It’s an effective and loud siren with true rise and fall, unlike other kits of the era that alternated between two fixed tones. The packaging was quite strong and idea for mail-order at the time:

The label sells the product (and shows the age):

The kit included every part required to work, apart from a PP3 battery, and a single instruction sheet with a good explanation of how the circuit works, and some data about the LM358:

… and as usual the PCB was ahead of its’ time with full silk-screen and solder mask:

Assembly was quite straight-forward. The design is quite compact, so a lot of vertical resistor mounting was necessary due to the lack of space. However it was refreshing to not have any links to fit. After around twenty minutes of relaxed construction, it was ready to test:

It’s a 1/2 watt speaker, however much louder than originally anticipated:

Once again, another complete and well-produced kit.

Conclusion

That was a lot of fun, and I’m off to make the matching square-wave oscillator for the frequency counter. Kudos to Colin for all those years of publication and helping people learn. Lots of companies bang on about offering tutorials and information on the Internet for free, but Colin has been doing it for over ten years. Check out his Talking Electronics website for a huge variety of knowledge, an excellent electronics course you can get on CD – and go easy on him if you have any questions.

Full-sized images available on flickr. This kit was purchased without notifying the supplier.

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.

Learn how to use the TI ADS1110 16-bit ADC with Arduino in chapter fifty-three of my Arduino Tutorials. The first chapter is here, the complete series is detailed here.

Updated 02/07/2013

Introduction

Moving on from the last chapter where we explained an 8-bit ADC, in this instalment we have the Texas Instruments ADS1110 – an incredibly tiny but useful 16-bit analogue-to-digital converter IC.  It can operate between 2.7 and 5.5 V so it’s also fine for Arduino Due and other lower-voltage development boards. This is a quick guide to get you going with the ADS1110 ready for further applications. Before continuing any further, please download the data sheet (pdf) as it will be useful and referred to during this tutorial. The ADS1110 gives you the option of a more accurate ADC than offered by the Arduino’s 10-bit ADCs – and it’s relatively easy to use. The only block for some is the package type – it’s only available in SOT23-6:

So unless you’re making a customised PCB, some sort of breakout will be required. One useful example is the Schmartboard we reviewed earlier:

The ADS1110 uses the I2C bus for communication, so if this is new to you – please review the I2C tutorials before continuing. And as there’s only six pins you can’t set the bus address – instead, you can select from six variants of the ADS1110 – each with their own address (see page two of the data sheet). As you can see the in the photo above, ours is marked “EDO” which matches to the bus address 1001000 or 0x48h. And with the example circuits we’ve used 10kΩ pull-up resistors on the I2C bus. You can use the ADS1110 as either a single-ended or differential ADC –  But first we need to examine the configuration register which is used to control various attributes, and the data register.

Configuration register

Turn to page eleven of the data sheet. The configuration register is one byte in size, and as the ADS1110 resets on a power-cycle – you need to reset the register if your needs are different to the defaults. The data sheet spells it out quite neatly… bits 0 and 1 determine the gain setting for the PGA (programmable gain amplifier). If you’re just measuring voltages or experimenting, leave these as zero for a gain of 1V/V. Next, the data rate for the ADS1110 is controlled with bits 2 and 3. If you have continuous sampling turned on, this determines the number of samples per second taken by the ADC.

After some experimenting with an Arduino Uno we found the values returned from the ADC were a bit off when using the fastest rate, so leave it as 15 SPS unless required otherwise. Bit 4 sets either continuous sampling (0) or one-off sampling (1). Ignore bits 5 and 6, however they’re always set as 0. Finally bit 7 – if you’re in one-off sampling mode, setting it to 1 requests a sample – and reading it will tell you if the returned data is new (0) or old (1). You can check that the value measured is a new value – if the first bit of the configuration byte that comes after the data is 0, it’s new. If it returns 1 the ADC conversion hasn’t finished.

Data register

As the ADS1110 is a 16-bit ADC, it returns the data over two bytes – and then follows with the value of the configuration register. So if you request three bytes the whole lot comes back. The data is in “two’s complement” form, which is a method of using signed numbers with binary. Converting those two bytes is done by some simple maths. When sampling at 15 SPS, the value returned by the ADS1110 (not the voltage)  falls between -32768 and 32767. The higher byte of the value is multiplied by 256, then added to the lower byte – which is then multiplied by 2.048 and finally divided by 32768. Don’t panic, as we do this in the example sketch below.

In this mode you can read a voltage that falls between zero and 2.048 V (which also happens to be the inbuilt reference voltage for the ADS1110). The example circuit is simple (from the data sheet):

Don’t forget the 10kΩ pull-up resistors on the I2C bus. The following sketch uses the ADS1110 in the default mode, and simply returns the voltage measured:

Once uploaded, connect the signal to measure and open the serial monitor – you’ll be presented with something similar to:

If you need to alter the gain of the internal programmable gain amplifier of the ADC – you’ll need to write a new byte into the configuration register using:

before requesting the ADC data. This would be 0x8D, 0x8E or 0x8F for gain values of 2, 4 and 8 respectively – and use 0x8C to reset the ADS1110 back to default.

In this mode you can read the difference between two voltages that each fall between zero and 5 V. The example circuit is simple (from the data sheet):

We must note here (and in the data sheet) that the ADS1110 can’t accept negative voltages on either of the inputs. You can use the previous sketch for the same results – and the resulting voltage will be the value of Vin- subtracted from Vin+. For example, if you had 2 V on Vin+ and 1 V on Vin- the resulting voltage would be 1 V (with the gain set to 1).

Conclusion

Once again I hope you found this of interest, and possibly useful. 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 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.

## Tutorial – Arduino and PCF8591 ADC DAC IC

Learn how to use the NXP PCF 8591 8-bit A/D and D/A IC with Arduino in chapter fifty-two of my Arduino Tutorials. The first chapter is here, the complete series is detailed here.

Updated 17/06/2013

Introduction

Have you ever wanted more analogue input pins on your Arduino project, but not wanted to fork out for a Mega? Or would you like to generate analogue signals? Then check out the subject of our tutorial – the NXP PCF8591 IC. It solves both these problems as it has a single DAC (digital to analogue) converter as well as four ADCs (analogue to digital converters) – all accessible via the I2C bus. If the I2C bus is new to you, please familiarise yourself with the readings here before moving forward.

The PCF8591 is available in DIP form, which makes it easy to experiment with:

You can get them from the usual retailers. Before moving on, download the data sheet. The PCF8591 can operate on both 5V and 3.3V so if you’re using an Arduino Due, Raspberry Pi or other 3.3 V development board you’re fine. Now we’ll first explain the DAC, then the ADCs.

Using the DAC (digital-to-analogue converter)

The DAC on the PCF8591 has a resolution of 8-bits – so it can generate a theoretical signal of between zero volts and the reference voltage (Vref) in 255 steps. For demonstration purposes we’ll use a Vref of 5V, and you can use a lower Vref such as 3.3V or whatever you wish the maximum value to be … however it must be less than the supply voltage. Note that when there is a load on the analogue output (a real-world situation), the maximum output voltage will drop – the data sheet (which you downloaded) shows a 10% drop for a 10kΩ load. Now for our demonstration circuit:

Note the use of 10kΩ pull-up resistors on the I2C bus, and the 10μF capacitor between 5V and GND. The I2C bus address is set by a combination of pins A0~A2, and with them all to GND the address is 0x90. The analogue output can be taken from pin 15 (and there’s a seperate analogue GND on pin 13. Also, connect pin 13 to GND, and circuit GND to Arduino GND.

To control the DAC we need to send two bytes of data. The first is the control byte, which simply activates the DAC and is 1000000 (or 0x40) and the next byte is the value between 0 and 255 (the output level). This is demonstrated in the following sketch:

Did you notice the bit shift of the bus address in the #define statement? Arduino sends 7-bit addresses but the PCF8591 wants an 8-bit, so we shift the byte over by one bit.

The results of the sketch are shown below, we’ve connected the Vref to 5V and the oscilloscope probe and GND to the analogue output and GND respectively:

If you like curves you can generate sine waves with the sketch below. It uses a lookup table in an array which contains the necessary pre-calculated data points:

And the results:

For the following DSO image dump, we changed the Vref to 3.3V – note the change in the maxima on the sine wave:

Now you can experiment with the DAC to make sound effects, signals or control other analogue circuits.

If you’ve used the analogRead() function on your Arduino (way back in Chapter One) then you’re already familiar with an ADC. With out PCF8591 we can read a voltage between zero and the Vref and it will return a value of between zero and 255 which is directly proportional to zero and the Vref. For example, measuring 3.3V should return 168. The resolution (8-bit) of the ADC is lower than the onboard Arduino (10-bit) however the PCF8591 can do something the Arduino’s ADC cannot. But we’ll get to that in a moment.

First, to simply read the values of each ADC pin we send a control byte to tell the PCF8591 which ADC we want to read. For ADCs zero to three the control byte is 0x00, 0x01, ox02 and 0x03 respectively. Then we ask for two bytes of data back from the ADC, and store the second byte for use. Why two bytes? The PCF8591 returns the previously measured value first – then the current byte. (See Figure 8 in the data sheet). Finally, if you’re not using all the ADC pins, connect the unused ones to GND.

The following example sketch simply retrieves values from each ADC pin one at a time, then displays them in the serial monitor:

Upon running the sketch you’ll be presented with the values of each ADC in the serial monitor. Although it was a simple demonstration to show you how to individually read each ADC, it is a cumbersome method of getting more than one byte at a time from a particular ADC.

To do this, change the control byte to request auto-increment, which is done by setting bit 2 of the control byte to 1. So to start from ADC0 we use a new control byte of binary 00000100 or hexadecimal 0x04. Then request five bytes of data (once again we ignore the first byte) which will cause the PCF8591 to return all values in one chain of bytes. This process is demonstrated in the following sketch:

Previously we mentioned that the PCF8591 can do something that the Arduino’s ADC cannot, and this is offer a differential ADC. As opposed to the Arduino’s single-ended (i.e. it returns the difference between the positive signal voltage and GND, the differential ADC accepts two signals (that don’t necessarily have to be referenced to ground), and returns the difference between the two signals. This can be convenient for measuring small changes in voltages for load cells and so on.

Setting up the PCF8591 for differential ADC is a simple matter of changing the control byte. If you turn to page seven of the data sheet, then consider the different types of analogue input programming. Previously we used mode ’00’ for four inputs, however you can select the others which are clearly illustrated, for example:

So to set the control byte for two differential inputs, use binary 00110000 or 0x30. Then it’s a simple matter of requesting the bytes of data and working with them. As you can see there’s also combination single/differential and a complex three-differential input. However we’ll leave them for the time being.

Conclusion

Hopefully you found this of interest, whether adding a DAC to your experiments or learning a bit more about ADCs. We’ll have some more analogue to digital articles coming up soon, so stay tuned. 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 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.

## Kit Review – JYE Tech FG085 DDS Function Generator

Introduction

There has been a lot of talk lately about inexpensive DDS (direct digital synthesis) function generators, and I always enjoy a kit – so it was time to check out the subject of this review. It’s the “FG085 miniDDS function generator” from JYE Tech. JYE is a small company in China that makes inexpensive test equipment kits, for example their capacitance meter (my first kit review!) and DSO. The capacitance meter was good, the DSO not so good – so let’s hope this is better than their last efforts.

Assembly

The instructions (AssemblyGuide_085G) are much better than previous efforts, and if you have bought the kit – read them. The kit arrives in a large zip-lock bag, with the following bundle of parts:

The AC adaptor is 100~240V in, 15V DC out. Everything is included with the kit including a short BNC to alligator clips lead for output. The PCBs are very good, with a nice solder mask and silk screen:

and back:

At this point we realise that most of the work is already done. There’s two microcontrollers ATmega48 and ATmega168- one for display and user-interface control, and the other for function generation. It takes only a few minutes to solder in the through-hole parts, headers and sockets:

… then you flip over the PCB and add the LCD:

… followed by the buttons and rotary encoder. From previous research this is the part that causes people a lot of trouble – so read carefully. There’s a lot of buttons – and if they aren’t inserted into the PCB correctly your life will become very difficult. The buttons must be inserted a certain way – they’re “polarised” – for example:

As you can see above, one side has a double-vertical line and the other side has a single. When you fit the buttons to the PCB – the side with the double-vertical must face the left-hand side of the PCB – the side with the DC socket. For example:

Furthermore, don’t be in a rush and put all the buttons in then try to solder them all at once.  Do them one at a time, and hold them tight to the PCB with some blu-tac or similar. If they don’t sit flush with the PCB the front panel won’t fit properly and the buttons will stick when in use. So exercise some patience, and you’ll be rewarded with an easy to use function generator. Rush them in and you’ll be very unhappy. I warned you! After fitting each button, test fit the front panel to check the alignment, for example:

Then you end up with nicely-aligned buttons:

… which all operate smoothly when the panel is fitted:

After the buttons comes the rotary encoder. Be very careful when fitting it to the PCB – the data legs are really weak, and bend without much effort. If you push in the encoder, be mindful of the legs not going through the holes and bending upwards. Furthermore, when soldering in the encoder note that you’re really close to an electrolytic – you don’t want to stab it with a hot iron:

The CP2012 chip in the image above is for the USB interface. More on that later. Now the next stage is the power-test. Connect DC power and turn it on – you should be greeted by a short copyright message followed by the operation display:

If you didn’t – remove the power and check your soldering –  including the capacitor polarities and look for bridges, especially around the USB socket. Now it’s time to fit the output BNC socket. For some reason only known to the designers, they have this poking out the front of the panel for the kit – however previous revisions have used a simple side-entry socket. Thus you need to do some modifications to the supplied socket. First, chop the tag from the sprocket washer:

… then remove the paper from the front panel:

Now solder a link to the washer in a vertical position:

… then fit the BNC socket to the panel, with the washer aligned as such:

Finally, align the top panel with the PCB so the BNC socket pin and washer link drop into the PCB and solder them in:

If you want to use the servo mode, solder three short wires that can attach to a servo form the three “output” pads between the BNC and USB socket.

Finally, screw in the panels and you’re finished!

Using the function generator

Operation is quite simple, and your first reference should be the manual (manual.pdf). The display defaults to normal function generator mode at power-up – where you can adjust the frequency, offset, amplitude and type of output – sine, square, triangle, ramp up, ramp down, staircase up and down:

The ranges for all functions is 0~10 khz, except for sine which can hit 200 kHz. You can enter higher frequencies, such as up to 250 kHz for sine – but the results aren’t so good.

Instead of filling this review with lots of screen dumps from an oscilloscope to demonstrate the output – I’ve made the following video where you can see various functions being displayed on a DSO:

You can also create signals to test servos, with adjustable pulse-width, amplitude and cycle times. However you’ll need to solder three wires onto the PCB (next to the BNC socket area) to attach to the servo.

According to the user manual and various retailers’ websites – the FG085 can generate frequency sweeping signals. These are signals that sweep from a start to as finish frequency over a period of time. However the firmware on the supplied unit is old and needs updating to enable this function. You can download the firmware in .hex file format from here. Then go and dig up an AVR programmer and avrdudeAt the time of writing we had some issues with the signature not being recognised when updating the firmware, and solidly bricked the FG085. Our fault – so when that’s sorted out we’ll update the review – stay tuned.

There is also a USB port on the side – after installing CP2102 drivers in Windows we could connect at 115200 bps with terminal, however all the FG085 returned was the firmware version number. Perhaps later on the designers will update the firmware to allow for PC control. Somehow I wouldn’t bank on it.

Conclusion

It’s an interesting piece of equipment. Putting the firmware upgrade issues to one side, the FG085 does what it sets out to do. During testing it worked well, and we didn’t come across any obvious inaccuracies during use.  The price varies between US\$43 and \$50 – so for that money it’s  a good kit. Just take care during construction and you’ll be fine.

The function generator is available in kit form or assembled, with or without panels from China. The kit version with panels is also available from Sparkfun (KIT-11394) and their resellers. Full-sized images available on flickr. This kit was purchased and reviewed without notifying the supplier.

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.

## Project: Clock Two – Single digit clock

Let’s hack an Ikea lamp into a single-digit clock! How? Read on…

Updated 18/03/2013

Time for another instalment in my irregular series of clock projects. (Or should that be “Time for another instalment in the series of irregular clock projects”?) In contrast with the extreme “blinkiness” of Clock One, in this article we describe how to build this single-digit digital clock:

Once again the electronics of the clock will be based from an Arduino-compatible board with a DS1307 real-time clock IC added to the board. On top of this we add a shield with some extra circuitry and two buttons – but more on this later. The inspiration for this clock came from a product that was recently acquired at Ikea – the “Kvart” work lamp, for example:

If you are shopping for one, here are the Ikea stock details:

The goal is to place the electronics of the clock in the base, and have one single-digit LED display at the top of the neck which will blink out the digits. There will be two buttons under the base that are used to set the time. It will be powered by a 9V battery or an AC adaptor which is suitable for a typical Arduino board.

Construction

This article is a diary of my construction, and you can always use your own knowledge and initiative. It is assumed that you have a solid knowledge of the basics of the Arduino system.  If not, review my series of tutorials available from here. Furthermore, feel free to modify the design to work with what you have available – I hope this article can be of some inspiration to you.

Software

It is much easier to prototype the clock and get the Arduino sketch working how you like it before breaking down the lamp and building up the clock. To do this involves some jumper wires and a solderless breadboard, for example:

Although there are four buttons on the board we only use two. They are connected to digital pins eight and nine (with 10k pull-down resistors). The LED display segments a~g are connected to Arduino digital pins 0~6 respectively. The decimal point is connected to the pulse output pin of the DS1307 – which will be set to a 1Hz output to have a nice constant blinking to show the clock is alive and well.

If you are unfamiliar with operating the DS1307 real-time clock IC please review this tutorial. Operation of the clock has been made as simple for the user as possible. To set the time, they press button A (on digital eight) while the current time is being displayed, after which point the user can select the first digit (0~2) of the time by pressing button A. Then they press button B (on digital nine) to lock it in and move to the second digit (0~9) which is again chosen with button A and selected with button B. Then they move onto the digits in the same manner.

After this process the new time is checked for validity (so the user cannot enter invalid times such as 2534h) – and is ok, the clock will blink the hyphen twice and then carry on with the new time. If the entered time is invalid, the clock reverts back to the current time. This process is demonstrated in the following video clip:

Hardware

The parts required to replicate the Clock Two in this article are:

• One Arduino-compatible board with DS1307 real-time clock IC as described in this article
• One Arduino protoshield and header pins
• One common-cathode 7-segment LED display of your choosing
• Seven current-limiting resistors to reduce the output current from Arduino digital outputs going to the LED segments. In our example we use a 560 ohm resistor network to save time
• Two buttons and two 10k ohm pull-down resistors
• One meter of nine-core wire that will fit inside the neck and stand of the Kvart lamp – an external diameter of less than 6mm will be fine
• And of course – the lamp

The protoshield is used to hold the buttons, resistor network and the terminus for the wires between the LED display and the Arduino digital outputs, for example:

At this stage you will need to do some heavy deconstruction on the lamp. Cut off the mains lead at the base and remove the plastic grommet from the stand that surrounded the AC lead. Next,  with some elbow grease you can twist off the lamp-shade unit from the end of the flexible neck. You could always reuse the lamp head and AC lead if wired by a licensed electrician.

Now you need to feed the multicore wire through the neck and down to the base of the lamp. You can pull it through the hole near the base, and then will need to drill a hole in the base to feed it through to the electronics as such:

Take care when feeding the cable though so you don’t nick the insulation as shown above. Leave yourself a fair bit of slack at the top which will make life easier when soldering on the LED display, for example:

The next step is to solder the wires at the top to the LED display. Make notes to help recall which wires are soldered to the pins of the display. If your soldering skills (like mine) aren’t so good, use heatshrink to cover the soldering:

Most displays will have two GND pins, so bridge them so you only need to use one wire in the multicore back to base:

At this point use the continuity function of a multimeter or a low-voltage power source to test each LED segment using the other end of the cable protruding from the base. Once you are satisfied the segments have been soldered correctly, carefully draw the cable back through the neck and base in order to reduce the slack between the display and the top of the lamp neck. Then solder the individual LED segment wires to the protoshield.

Now if you have not already done so, upload the sketch into the Arduino board – especially if you are going to permanently mount the circuitry into the base. A simple method of mounting would be using  a hot glue gun, but for the purpose of demonstration we have just used blu-tac:

Although this does look a little rough, we are using existing stock which kept the cost down. If you are going to power the clock with an AC adaptor, you will also need to cut out small opening to allow the lead to protrude from the side of the base. And now for the resulting clock – our Clock Two:

So there you have it, the second of many clocks we plan to describe in the future.

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.

## Using an ATtiny as an Arduino

Learn how to use ATtiny45 and ATtiny85 microcontrollers with Arduino in chapter forty-four of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – a series of articles on the Arduino universe. The first chapter is here, the complete series is detailed here.

Updated 07/10/2014

Did you know you can use an Atmel ATtiny45 or ATtiny85 microcontroller with Arduino software? Well you do now. The team at the High-Low Tech Group at MIT have published the information and examples on how to do this, and it looked like fun – so the purpose of this article is to document my experience with the ATtiny and Arduino and share the instructions with you in my own words. All credit goes to the interesting people at the MIT HLT Group for their article and of course to Alessandro Saporetti for his work on making all this possible.

Introduction

Before anyone gets too excited – there are a few limitations to doing this…

Limitation one – the ATtiny has “tiny” in the name for a reason:

it’s the one on the left

Therefore we have less I/O pins to play with. Consider the pinout for the ATtiny from the data sheet:

So as you can see we have thee analogue inputs (pins 7, 3 and 2) and two digital outputs with PWM (pins 5 and 6). Pin 4 is GND, and pin 8 is 5V.

Limitation two – memory. The ATtiny45 has 4096 bytes of flash memory available, the -85 has 8192. So you may not be controlling your home-built R2D2 with it.

Limitation three – available Arduino functions. As stated by the HLT article, the following commands are supported:

Other functions may work or become available over time.

Limitation four – You need Arduino IDE v1.0.1 or higher, except for v1.0.2. So v1.0.3 and higher is fine.

So please keep these limitations in mind when planning your ATtiny project.

Getting Started

You can use an existing Arduino-compatible board as a programmer with some external wiring. Before wiring it all up – plug in your Arduino board, load the IDE and upload the ArduinoISP sketch which is in the File>Examples menu. Whenever you want to upload a sketch to your ATtiny, you need to upload the ArduinoISP sketch to your Arduino first. Consider this sketch the “bridge” between the IDE and the ATtiny.

Next, build the circuit as shown below:

Depending on the Arduino board you’re using, you may or may not need the 10uF capacitor between Arduino RST and GND. Follow the schematic above each time you want to program the ATtiny.

Software

From a software perspective, to use the ATtinys you need to add some files to your Arduino IDE. First, download this zip file. Then extract the”attiny” folder and copy it to the “hardware” folder which sits under your main Arduino IDE folder, for example:

Now restart the Arduino IDE. As you’re using the Arduino as a programmer, you need select “Arduino as ISP” – which is found in the Tools>Programmer menu. Next – select the board type using the Tools>Board  menu. Select the appropriate ATtiny that you’re using – with the 1 MHz internal clock option. Now you can enter and upload your ATtiny sketch. When uploading sketches you may see error messages as shown below:

The message is “normal” in this situation, so nothing to worry about.

Creating Arduino sketches for ATtinys

When creating your sketches, note that the pin number allocations are different for ATtinys in the IDE. Note the following pin number allocations:

• digital pin zero is physical pin five (also PWM)
• digital pin one is physical pin six (also PWM)
• analogue input two is physical pin seven
• analogue input three is physical pin two
• analogue input four is physical pin three

For a quick demonstration, load the Blink example sketch – File>Examples>1. Basics>Blink. Change the pin number for the digital output from 13 to 0. For example:

Upload the sketch using the methods described earlier. If you’re using programmer method one, your matching circuit is:

If you’re using programmer method two, this will blink the on-board LED.

Final example

We test the digital outputs with digital and PWM outputs using two LEDs instead of one:

And the sketch:

And a quick demonstration video:

So there you have it – another interesting derivative of the Arduino system. Once again, thanks and credit to Alesssandro Saporetti and the MIT HLT Group for their published information. And if you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book “Arduino Workshop”.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column, or join our forum – dedicated to the projects and related items on this website.

## Review – Tenma 72-7222 Digital Clamp Multimeter

The purpose of this article is to examine the Tenma 72-7222 Digital Clamp Multimeter supplied for review by element-14/Farnell/Newark. The Tenma is a strongly featured yet inexpensive piece of test equipment – and considerably good value when you consider there is a current clamp for measuring high AC currents. So let’s have a look and see what we have.

Initial Impression

The Tenma arrives in a retail box, and generally nicely packaged. Naturally this has nothing to do with the performance of the meter at all, but at least they made an effort:

Opening up we find a nicely rounded group of items: the meter itself, some no-name AAA cells, test leads, a thermocouple for temperature measurement, a surprisingly articulate and well-written user manual, and the unit itself – all within a nice pouch. Wow – a pouch. Agilent? Fluke? All that money for a DMM and you don’t include a pouch?

Recent test equipment reviewers have made pulling apart the unit part of the review – so here goes… the back comes off easily:

No user-replaceable fuses… instead a PTC. A closer look at the PCB:

A very neat and organised PCB layout. There are plastic tabs that hold the PCB in along with a screw, however the case flexed too much for me to warrant removing the PCB completely. The spring for the clamp meter is locked in nicely and very strong, it won’t give up for a long time. Pulling the clamp base out reveals the rest of the PCB:

Installation of the battery is two stage procedure, first you need to remove a screw and then slide out the rear door:

… then insert the AAA cells into a frame, which is then inserted inside the unit:

The physical feel of the unit is relative to the purchase price, the plastic is simple and could be quite brittle if the unit was dropped from a height. The user manual claims the unit can be dropped from up to a height of one metre. Onto carpet? Yes. Concrete? Perhaps not. However like all test equipment one would hope the user would take care of it whenever possible. The clamp meter is very strong due to the large spring inside the handle, which can be opened up to around 28mm. The included leads are just on one meter long including the length of the probe:

The leads are rated to Category I 1000V (overkill – the meter can’t go that high) and 600 V Category II – “This category refers to local-level electrical distribution, such as that provided by a standard wall outlet or plug in loads (for example, 115 AC voltage for U.S. or 200 AC voltage for Europe). Examples of Measurement Category II are measurements performed on household appliances, portable tools, and similar modules” – definition from from National Instruments.  Unlike discount DMMs from unknown suppliers you can trust the rating to be true – otherwise element-14 wouldn’t be selling it.

Unit Specifications

• Voltage Measuring Range DC:200mV, 2V, 20V, 200V, 600V
• Voltage Measuring Range AC:2V, 20V, 200V, 600V
• Current Measuring Range AC:2A, 20A, 200A, 400A
• Resistance Measuring Range:200ohm, 2kohm, 20kohm, 200kohm, 2Mohm, 20Mohm
• Temperature Measuring Range:-40°C to +1000°C
• DMM Response Type:True RMS
• DMM Functions:AC Current, AC/DC Voltage, Resistance, Temperature
• Ranging:Auto
• Display Count:1999
• AC Current Range Accuracy:± (1.5% + 5d)
• AC Voltage Range Accuracy:± (1.2% + 5d)
• Accuracy:± (1.0% + 3d)
• Current AC Max:400A
• Current Range AC:2A, 20A, 200A, 400A
• DC Voltage Range Accuracy1:± (0.8% + 1d)
• Resistance Range Accuracy:± (1.0% + 2d)
• Temperature Measuring Range:-40°C to +1000°C

The only measurement missed out on is DC current, however there is the Tenma 72-7224 which has DC current and frequency ranges. Finally, all the modes and buttons can be selected while holding the meter with one hand – for both left- and right-handed folk.

Measurement experience

Normally I would compare the measurements against my Agilent U1272A, however it’s out to lunch. Instead, a Fluke 233. First, AC voltage from the mains:

Next, a few DC voltage measurements:

Now for some resistance measurements. Higher values near the maximum of 20M Ohm can take around four seconds to measure:

Forward voltage of a 1N4004 diode:

Now off to the kitchen for some more measurements – first with the thermocouple:

The boiling water test – 100 degrees Celsius (you can also select Fahrenheit if so inclined):

And now to test out the AC current clamp meter function with a 10A kettle at boiling point. First, using the 20A current range:

And then again on the 400A current range:

As always, it’s best to use the multimeter range that more closely corresponds with the current under test. The meter also has a continuity test with a beeper, however it was somewhat slow and would often take around one second to register – so nothing too impressive on that front. The meter can record the maximum value with the grey button, or hold a reading using the yellow button.

Conclusion

The Tenma 72-7222 works as advertised, and as expected. It is a solid little unit that if looked after should last a few years at a minimum. It certainly has a few limitations, such as the 1999 count display, lack of backlight, and the average continuity function. But don’t let that put you off. For the price – under Au\$30 – it is a certified deal. If you need a clamp current meter for odd jobs or a casual-use multimeter and you are on a limited budget, the Tenma will certainly prove a worthwhile purchase. Full-size images are available on Flickr.

You can purchase a Tenma 72-7222 from element-14Farnell and Newark.

[Note – The Tenma 72-7222 Digital Clamp Multimeter was a promotional consideration from element-14/Farnell/Newark]

## Tutorial: Arduino timing methods with millis()

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

[Updated 20/01/2013]

In this article we introduce the millis(); function and put it to use to create various timing examples.

Millis? Nothing to do with lip-syncers… hopefully you recognised milli as being the numerical prefix for one-thousandths; that is multiplying a unit of measure by 0.001 (or ten to the power of negative 3). Interestingly our Arduino systems will count the number of milliseconds (thousands of a second) from the start of a sketch running until the count reaches the maximum number capable of being stored in the variable type unsigned long (a 32-bit [four byte] integer – that ranges from zero to (2^32)-1.

(2^32)-1, or 4294967295 milliseconds converts to 49.71027-odd days. The counter resets when the Arduino is reset, it reaches the maximum value or a new sketch is uploaded. To get the value of the counter at a particular juncture, just call the function – for example:

Where start is an unsigned long variable. Here is a very simple example to show you millis() in action:

The sketch stores the current millis count in start, then waits one second, then stores the value of millis again in finished. Finally it calculates the elapsed time of the delay.  In the following screen dump of the serial monitor, you can see that the duration was not always exactly 1000 milliseconds:

To put it simply, the millis function makes use of an internal counter within the ATmega microcontroller at the heart of your Arduino. This counter increments every clock cycle – which happens (in standard Arduino and compatibles) at a clock speed of 16 Mhz. This speed is controlled by the crystal on the Arduino board (the silver thing with T16.000 stamped on it):

Crystal accuracy can vary depending on external temperature, and the tolerance of the crystal itself. This in turn will affect the accuracy of your millis result. Anecdotal experience has reported the drift in timing accuracy can be around three or four seconds per twenty-four hour period. If you are using a board or your own version that is using a ceramic resonator instead of a crystal, note that they are not as accurate and will introduce the possibility of higher drift levels. If you need a much higher level of timing accuracy, consider specific timer ICs such as the Maxim DS3232.

Now we can make use of the millis  for various timing functions. As demonstrated in the previous example sketch, we can calculate elapsed time. To take this idea forward, let’s make a simple stopwatch. Doing so can be as simple or as complex as necessary, but for this case we will veer towards simple. On the hardware perspective, we will have two buttons – Start and Stop – with the 10k ohm pull-down resistors connected to digital pins 2 and 3 respectively.

When the user presses start the sketch will note the value for millis – then after stop is pressed, the sketch will again note the value for millis, calculate and display the elapsed time. The user can then press start to repeat the process, or stop for updated data. Here is the sketch:

The calls to delay() are used to debounce the switches – these are optional and their use will depend on your hardware. Below is an example of the sketch’s serial monitor output – the stopwatch has started, and then button two pressed six times across periods of time:

If you had a sensor at the start and end of a fixed distance, speed could be calculated: speed = distance ÷ time.

You can also make a speedometer for a wheeled form of motion, for example a bicycle. At the present time I do not have a bicycle to mess about with, however we can describe the process to do so – it is quite simple. (Disclaimer – do so at your own risk etc.)  First of all, let’s review the necessary maths. You will need to know the circumference of the wheel. Hardware – you will need a sensor. For example – a reed switch and magnet. Consider the reed switch to be a normally-open button, and connect as usual with a 10k ohm pull-down resistor. Others may use a hall-effect sensor – each to their own). Remember from maths class:

To calculate the circumference – use the formula:

circumference = 2πr

where r is the radius of the circle. Now that you have the wheel circumference, this value can be considered as our ‘fixed distance’, and therefore the speed can be calculated by measuring the elapsed time between of a full rotation.

Your sensor – once fitted – should act in the same method as a normally-open button that is pushed every rotation. Our sketch will measure the time elapsed between every pulse from the sensor. To do this, our example will have the sensor output connected to digital pin 2 – as it will trigger an interrupt to calculate the speed. (Interrupts? See chapter three). The sketch will otherwise be displaying the speed on a normal I2C-interface LCD module. The I2C interface is suggested as this requires only 4 wires from the Arduino board to the LCD – the less wires the better.

Here is the sketch for your perusal:

There isn’t that much going on – every time the wheel completes one revolution the signal from the sensor will go from low to high – triggering an interrupt which calls the function speedCalc(). This takes a reading of millis() and then calculates the difference between the current reading and the previous reading – this value becomes the time to cover the distance (which is the circumference of the wheel relative to the sensor – stored in

and is measured in metres). It finally calculates the speed in km/h and MPH. Between interrupts the sketch displays the updated speed data on the LCD as well as the raw time value for each revolution for curiosity’s sake. In real life I don’t think anyone would mount an LCD on a bicycle, perhaps an LED display would be more relevant.

In the meanwhile, you can see how this example works in the following short video clip. Instead of a bike wheel and reed switch/magnet combination, I have connected the square-wave output from a function generator to the interrupt pin to simulate the pulses from the sensor, so you can get an idea of how it works:

That just about sums up the use of millis() for the time being. There is also the micros(); function which counts microseconds. So there you have it – another practical function that can allow more problems to be solved via the world of Arduino. As always, now it is up to you and your imagination to find something to control or get up to other shenanigans.

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.

## Tutorial: Arduino and the SPI bus part II

This is chapter thirty-six of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A seemingly endless series of articles on the Arduino universe. The first chapter is here, the complete series is detailed here

[Updated 10/01/2013]

This is the second of several chapters in which we are investigating the SPI data bus, and how we can control devices using it with our Arduino systems. If you have not done so already, please read part one of the SPI articles. Again we will learn the necessary theory, and then apply it by controlling a variety of devices. As always things will be kept as simple as possible.

First on our list today is the use of multiple SPI devices on the single bus. We briefly touched on this in part one, by showing how multiple devices are wired, for example:

Notice how the slave devices share the clock, MOSI and MISO lines – however they both have their own chip select line back to the master device. At this point a limitation of the SPI bus becomes prevalent – for each slave device we need another digital pin to control chip select for that device. If you were looking to control many devices, it would be better to consider finding I2C solutions to the problem. To implement multiple devices is very easy. Consider the example 34.1 from part one – we controlled a digital rheostat. Now we will repeat the example, but instead control four instead of one. For reference, here is the pinout diagram:

Doing so may sound complex, but it is not. We connect the SCK, MOSI and  MISO pins together, then to Arduino pins D13, D11, D12 respectively. Each CS pin is wired to a separate Arduino digital pin. In our example rheostats 1 to 4 connect to D10 through to D7 respectively. To show the resistance is changing on each rheostat, there is an LED between pin 5 and GND and a 470 ohm resistor between 5V and pin 6. Next, here is the sketch:

Although the example sketch may be longer than necessary, it is quite simple. We have four SPI devices each controlling one LED, so to keep things easy to track we have defined led1~led4 to match the chip select digital out pins used for each SPI device. Then see the first four lines in void setup(); these pins are set to output in order to function as required. Next – this is very important – we set the pins’ state to HIGH. You must do this to every chip select line! Otherwise more than one CS pins may be initially low in some instances and cause the first data sent from MOSI to travel along to two or more SPI devices. With LEDs this may not be an issue, but for motor controllers … well it could be.

The other point of interest is the function

We pass the value for the SPI device we want to control, and the value to send to the device. The value for l is the chip select value for the SPI device to control, and ranges from 10~7 – or as defined earlier, led1~4. The rest of the sketch is involved in controlling the LED’s brightness by varying the resistance of the rheostats. Now to see example 36.1 in action via the following video clip:

(If you are wondering what I have done to the Freetronics board in that video, it was to add a DS1307 real-time clock IC in the prototyping section).

Next on the agenda is a digital-to-analogue converter, to be referred to using the acronym DAC. What is a DAC? In simple terms, it accepts a numerical value between zero and a maximum value (digital) and outputs a voltage between the range of zero and a maximum relative to the input value (analogue). One could consider this to be the opposite of the what we use the function analogRead(); for. For our example we will use a Microchip MCP4921 (data sheet.pdf):

(Please note that this is a beginners’ tutorial and is somewhat simplified). This DAC has a 12-bit resolution. This means that it can accept a decimal number between 0 and 4095 – in binary this is 0 to 1111 1111 1111 (see why it is called 12-bit) – and the outpout voltage is divided into 4096 steps. The output voltage for this particular DAC can fall between 0 and just under the supply voltage (5V). So for each increase of 1 in the decimal input value, the DAC will output around 1.221 millivolts.

It is also possible to reduce the size of the voltage output steps by using a lower reference voltage. Then the DAC will consider the reference voltage to be the maximum output with a value of 4095. So (for example) if the reference voltage was 2.5V, each increase of 1 in the decimal input value, the DAC will output around 0.6105 millivolts. The minimum reference voltage possible is 0.8V, which offers a step of 200 microvolts (uV).

The output of a DAC can be used for many things, such as a function generator or the playback of audio recorded in a digital form. For now we will examine how to use the hardware, and monitoring output on an oscilloscope. First we need the pinouts:

By now these sorts of diagrams shouldn’t present any problems. In this example, we keep pin 5 permanently set to GND; pin 6 is where you feed in the reference voltage – we will set this to +5V; AVss is GND; and Vouta is the output signal pin – where the magic comes from 🙂 The next thing to investigate is the MCP4921’s write command register:

Bits 0 to 11 are the 12 bits of the output value; bit 15 is an output selector (unused on the MPC4921); bit 14 controls the input buffer; bit 13 controls an inbuilt output amplifier; and bit 12 can shutdown the DAC. Unlike previous devices, the input data is spread across two bytes (or a word of data). Therefore a small amount of work needs to be done to format the data ready for the DAC. Let’s explain this through looking at the sketch for example 36.2 that follows. The purpose of the sketch is to go through all possible DAC values, from 0 to 4095, then back to 0 and so on.

First. note the variable outputvalue – it is a word, a 16-bit unsigned variable. This is perfect as we will be sending a word of data to the DAC. We put the increasing/decreasing value for a into outputValue. However as we can only send bytes of data at a time down the SPI bus, we will use the function highbyte() to separate the high side of the word (bits 15~8) into a byte variable called data.

We then use the bitwise AND and OR operators to set the parameter bits 15~12. Then this byte is sent to the SPI bus. Finally, the function lowbyte() is used to send the low side of the word (bits 7~0) into data and thence down the SPI bus as well.

Now for our demonstration sketch:

And a quick look at the DAC in action via an oscilloscope:

By now we have covered in detail how to send data to a device on the SPI bus. But how do we receive data from a device?

Doing so is quite simple, but some information is required about the particular device. For the rest of this chapter, we will use the Maxim DS3234 “extremely accurate” real-time clock. Please download the data sheet (.pdf) now, as it will be referred to many times.

The DS3234 is not available in through-hole packaging, so we will be using one that comes pre-soldered onto a very convenient breakout board:

It only takes a few moments to solder in some header pins for breadboard use. The battery type is CR1220 (12 x 2.0mm, 3V); if you don’t have a battery you will need to short out the battery holder with some wire otherwise the IC will not work. Readers have reported that the IC doesn’t keep time if the USB and external power are both applied to the Arduino at the same time.

A device will have one or more registers where information is read from and written to. Look at page twelve of the DS3234 data sheet, there are twenty-three registers, each containing eight bits (one byte) of data. Please take note that each register has a read and write address. An example – to retrieve the contents of the register at location 08h (alarm minutes) and place it into the byte data we need to do the following:

Don’t forget to take note of  the function SPI.setBitOrder(MSBFIRST); in your sketch, as this also determines the bit order of the data coming from the device. To write data to a specific address is also quite simple, for example:

Up to this point, we have not concerned ourselves with what is called the SPI data mode. The mode determines how the SPI device interprets the ‘pulses’ of data going in and out of the device. For a well-defined explanation, please read this article. With some devices (and in our forthcoming example) the data mode needs to be defined. So we use:

to set the data mode, within void(setup);. To determine a device’s data mode, as always – consult the data sheet. With our DS3234 example, the mode is mentioned on page 1 under Features List.

Finally, let’s delve a little deeper into SPI via the DS3234. The interesting people at Sparkfun have already written a good demonstration sketch for the DS3234, so let’s have a look at that and deconstruct it a little to see what is going on. You can download the sketch below from here, then change the file extension from .c to .pde.

Don’t let the use of custom functions and loops put you off, they are there to save time. Looking in the function SetTimeDate();, you can see that the data is written to the registers 80h through to 86h (skipping 83h – day of week) in the way as described earlier (set CS low, send out address to write to, send out data, set CS high). You will also notice some bitwise arithmetic going on as well. This is done to convert data between binary-coded decimal and decimal numbers.

Why? Go back to page twelve of the DS3234 data sheet and look at (e.g.) register 00h/80h – seconds. The bits 7~4 are used to represent the ‘tens’ column of the value, and bits 3~0 represent the ‘ones’ column of the value. So some bit shifting is necessary to isolate the digit for each column in order to convert the data to decimal. For other ways to convert between BCD and decimal, see the examples using the Maxim DS1307 in chapter seven.

Finally here is another example of reading the time data from the DS3234:

So there you have it – more about the world of the SPI bus and how to control the devices within.

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.

## Tutorial: Arduino and the SPI bus

Learn how to use the SPI data bus with Arduino in chapter thirty-four of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A seemingly endless tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here

[Updated 10/01/2013]

This is the first of two chapters in which we are going to start investigating the SPI data bus, and how we can control devices using it with our Arduino systems. The SPI bus may seem to be a complex interface to master, however with some brief study of this explanation and practical examples you will soon become a bus master! To do this we will learn the necessary theory, and then apply it by controlling a variety of devices. In this tutorial things will be kept as simple as possible.

But first of all, what is it? And some theory…

SPI is an acronym for “Serial Peripheral Interface”. It is a synchronous serial data bus – data can travel in both directions at the same time, as opposed to (for example) the I2C bus that cannot do so. To allow synchronous data transmission, the SPI bus uses four wires. They are called:

• MOSI – Master-out, Slave-in. This line carries data from our Arduino to the SPI-controlled device(s);
• MISO – Master-in, Slave out. This line carries data from the SPI-controlled device(s) back to the Arduino;
• SS – Slave-select. This line tells the device on the bus we wish to communicate with it. Each SPI device needs a unique SS line back to the Arduino;
• SCK – Serial clock.

Within these tutorials we consider the Arduino board to be the master and the SPI devices to be slaves. On our Arduino Duemilanove/Uno and compatible boards the pins used are:

• SS – digital 10. You can use other digital pins, but 10 is generally the default as it is next to the other SPI pins;
• MOSI – digital 11;
• MISO – digital 12;
• SCK – digital 13;

Arduino Mega users – MISO is 50, MOSI is 51, SCK is 52 and SS is usually 53. If you are using an Arduino Leonardo, the SPI pins are on the ICSP header pins. See here for more information. You can control one or more devices with the SPI bus. For example, for one device the wiring would be:

Data travels back and forth along the MOSI and MISO lines between our Arduino and the SPI device. This can only happen when the SS line is set to LOW. In other words, to communicate with a particular SPI device on the bus, we set the SS line to that device to LOW, then communicate with it, then set the line back to HIGH. If we have two or more SPI devices on the bus, the wiring would resemble the following:

Notice how there are two SS lines – we need one for each SPI device on the bus. You can use any free digital output pin on your Arduino as an SS line. Just remember to have all SS lines high except for the line connected to the SPI device you wish to use at the time.

Data is sent to the SPI device in byte form. You should know by now that eight bits make one byte, therefore representing a binary number with a value of between zero and 255. When communicating with our SPI devices, we need to know which way the device deals with the data – MSB or LSB first. MSB (most significant bit) is the left-hand side of the binary number, and LSB (least significant bit) is the right-hand side of the number. That is:

Apart from sending numerical values along the SPI bus, binary numbers can also represent commands. You can represent eight on/off settings using one byte of data, so a device’s parameters can be set by sending a byte of data. These parameters will vary with each device and should be illustrated in the particular device’s data sheet. For example, a digital potentiometer IC with six pots:

This device requires two bytes of data. The ADDR byte tells the device which of six potentiometers to control (numbered 0 to 5), and the DATA byte is the value for the potentiometer (0~255). We can use integers to represent these two values. For example, to set potentiometer number two to 125, we would send 2 then 125 to the device.

How do we send data to SPI devices in our sketches?

First of all, we need to use the SPI library. It is included with the default Arduino IDE installation, so put the following at the start of your sketch:

Next, in void.setup() declare which pin(s) will be used for SS and set them as OUTPUT. For example,

where ss has previously been declared as an integer of value ten. Now, to activate the SPI bus:

and finally we need to tell the sketch which way to send data, MSB or LSB first by using

or

When it is time to send data down the SPI bus to our device, three things need to happen. First, set the digital pin with SS to low:

Then send the data in bytes, one byte at a time using:

Value can be an integer/byte between zero and 255. Finally, when finished sending data to your device, end the transmission by setting SS high:

Sending data is quite simple. Generally the most difficult part for people is interpreting the device data sheet to understand how commands and data need to be structured for transmission. But with some practice, these small hurdles can be overcome.

Now for some practical examples!

Time to get on the SPI bus and control some devices. By following the examples below, you should gain a practical understanding of how the SPI bus and devices can be used with our Arduino boards.

Example 34.1

Our first example will use a simple yet interesting part – a digital potentiometer (we also used one in the I2C tutorial). This time we have a Microchip MCP4162-series 10k rheostat:

Here is the data sheet.pdf for your perusal. To control it we need to send two bytes of data – the first byte is the control byte, and thankfully for this example it is always zero (as the address for the wiper value is 00h [see table 4-1 of the data sheet]).  The second byte is the the value to set the wiper, which controls the resistance. So to set the wiper we need to do three things in our sketch…

First, set the SS (slave select) line to low:

Then send the two byes of data:

Finally set the SS line back to high:

Easily done. Connection to our Arduino board is very simple – consider the MCP4162 pinout:

Vdd connects to 5V, Vss to GND, CS to digital 10, SCK to digital 13, SDI to digital 11 and SDO to digital 12. Now let’s run through the available values of the MCP4162 in the following sketch:

Now to see the results of the sketch. In the following video clip, a we run up through the resistance range and measure the rheostat value with a multimeter:

Before moving forward, if digital potentiometers are new for you, consider reading this short guide written by Microchip about the differences between mechanical and digital potentiometers.

Example 34.2

In this example, we will use the Analog Devices AD5204 four-channel digital potentiometer (data sheet.pdf). It contains four 10k ohm linear potentiometers, and each potentiometer is adjustable to one of 256 positions. The settings are volatile, which means they are not remembered when the power is turned off. Therefore when power is applied the potentiometers are all pre set to the middle of the scale. Our example is the SOIC-24 surface mount example, however it is also manufactured in DIP format as well.

To make life easier it can be soldered onto a SOIC breakout board which converts it to a through-hole package:

In this example, we will control the brightness of four LEDs. Wiring is very simple. Pinouts are in the data sheet.pdf.

And the sketch:

The function allOff() and allOn() are used to set the potentiometers to minimum and maximum respectively. We use allOff() at the start of the sketch to turn the LEDs off. This is necessary as on power-up the wipers are generally set half-way. Furthermore we use them in the blinkAll() function to … blink the LEDs. The function setPot() accepts a wiper number (0~3) and value to set that wiper (0~255). Finally the function indFade() does a nice job of fading each LED on and off in order – causing an effect very similar to pulse-width modulation.

Finally, here it is in action:

Example 34.3

In this example, we will use use a four-digit, seven-segment LED display that has an SPI interface. Using such a display considerably reduces the amount of pins required on the micro controller and also negates the use of shift register ICs which helps reduce power consumption and component count. The front of our example:

and the rear:

Thankfully the pins are labelled quite clearly. Please note that the board does not include header pins – they were soldered in after receiving the board. Although this board is documented by Sparkfun there seems to be issues in the operation, so instead we will use a sketch designed by members of the Arduino forum. Not wanting to ignore this nice piece of hardware we will see how it works and use it with the new sketch from the forum.

Again, wiring is quite simple:

• Board GND to Arduino GND
• Board VCC to Arduino 5V
• Board SCK to Arduino D12
• Board SI to Arduino D11
• Board CSN to Arduino D10

The sketch is easy to use, you need to replicate all the functions as well as the library calls and variable definitions. To display numbers (or the letters A~F) on the display, call the function

where a is the number to display, b is the base system used (2 for binary, 8 for octal, 10 for usual, and 16 for hexadecimal), and c is for padded zeros (0 =off, 1=on). If you look at the void loop() part of the example sketch, we use all four number systems in the demonstration. If your number is too large for the display, it will show OF for overflow. To control the decimal points, colon and the LED at the top-right the third digit, we can use the following:

After all that, here is the demonstration sketch for your perusal:

And a short video of the demonstration:

So there you have it – hopefully an easy to understand introduction to the world of the SPI bus and how to control the devices within. As always, now it is up to you and your imagination to find something to control or get up to other shenanigans. In the next SPI article we will look at reading and writing data via the SPI bus.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS usng 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.

## Review – Agilent U1272A True-RMS Digital Multimeter

This is our review of the Agilent Technologies U1272A water and dust resistant digital multimeter. It’s an extremely well specifed instrument, and according to the Agilent promotional material a better alternative to the venerable Fluke 87V. We also have examined the Bluetooth module.

Initial impression

The retail box as always is impressive and well decorated. Opening it up reveals a range of items:

including the meter itself, a calibration certificate and calibration results sheet, probe set, thermocouple, quick start guide and four AAA cells. It was a little disappointing to not find alligator clip adaptors nor a carrying case. For those interested, a full range  of documentation is available here.

The meter measures 207 x 92 x 59 mm (hwd) and is quite solid, not too heavy and surrounded by a good orange non-slip rubber layer. This no doubt helps provide some shock resistance, as this unit has survived a 2.5 meter drop from my ceiling to the concrete. It is refreshing to see that the keypad is laid out in an organised way, much better than the random-looking layout on the U1250 series:

The meter

Installing or changing the the battery (four AAA cells) is easily accomplished, and thankfully the fuses are also in the same compartment. The included AAA cells are thecheaper “GP brand”, and should do for the first few months. The dust and moisture protection is evident as shown by the o-ring seal around the perimeter of the compartment:

As mentioned earlier, the U1272A is water and dust resistant to IP54 specifications – 54 meaning “protected against dust limited ingress”/”protection against water sprayed from all directions – limited ingress permitted.”.

It is possible to turn the function selector with one hand whether you have the meter standing up or laying on your desk. The included test leads are just over 1200mm in length and are rated at Cat III 1000V, 15A. Two pairs of probes are included, with 4mm and 19mm tips:

Again, it is unfortunate that alligator-clip adaptors nor probes are included – these are very useful especially to those who are colourblind and need to sort resistors or measure tiny through-hole capacitors. Furthermore, a K-tyle thermocouple and non-compensation transfer adaptor are also included:

The thermocouple’s temperature range is -20~200 degrees Celsius, however with an optional thermocouple the maximum temperature can be increased to 1200 degrees C. As for the othermeasurement ranges, they are detailed in the data sheet which you can download here (.pdf).

Furthermore there is a diode test  function, and a continuity beeper. The backlight also flashes when using the continuity function which would be very convenient for those working in a noise environment. There has been some discussion around various forums as to the speed of the continuity function, so here is a small video demonstration of it in action:

In use

Although readers would not have any problem using the meter without reading the manual, doing so will illustrate the particular features of the U1272A as well as operation of the menu system that allow various settings to be changed. These can include: beep frequency (!), backlight duration, data communication parameters, default temperature units, scale conversion values, and activating the low-pass filter available when measuring DC voltage and current.

At the risk of shortening the battery life, I extended the backlight duration immediately to thirty seconds; and set temperature units to degrees Celsius. When taking measurements that only require the main numeric display, the ambient temperature is shown in the secondary numeric display. I must admit to discovering another feature by accident, if the leads are in the current and COM terminals and you select a non-current measurement function – the meter will beep like crazy, blink the backlight and show an error message. This is useful when you’re tired and probably should be doing something else.

Measuring AC voltage provides various data upon request. Apart from the RMS voltage value, you can also turn on a low-pass filter which blocks unwanted voltage above 1 kHz.

The frequency measurement function allows the display the frequency, duty cycle and pulse-width when measuring AC or DC current or voltage. Furthermore, you can display both voltage/current and also display the frequency, pulse-width and duty cycle at the same time, for example:

In a previous article the U1272A was used to measure frequency and duty cycle, which you can observe in the following short clip:

Measuring DC voltage is straightforward, and there is also the option to measure both AC and DC components and display them combined or separately, for example:

You can also display voltage as a decibel value relative to 1 mW (dBm) or a reference value of 1V (dBv). And the dB reference impedance can also be set to fall between 1 and 9999 ohms. Another interesting voltage measurement function is “Zlow”. Using this function, the meter changes to a very low input impedance, and can remove “ghost” voltages from the measurement by dissipating the coupling voltage. This function can also be used to test if a battery is still usable, if the voltage of the battery under test decreases slowly, it doesn’t have the capacity to deliver the required voltage. However I wouldn’t put a battery under this test method for too long due to the meter acting close to a short circuit.

Measuring resistance is simply done with the U1272A, and for more precise measurements one can short the probes to measure their resistance then set a null point so your measurements will not be affected by probe resistance. There is also an Agilent feature called SmartOhm which can be used to remove unexpected DC voltages that can add errors to resistance measurements. You can also use SmartOhm to measure leakage current or reverse current for junction diodes. I look forward to spending more time examining SmartOhm.

Furthermore, one can also measure conductance (the reciprocal of resistance) which is measured in Siemens. According to the manual one can measure extremely high resistance values up to 100 gigaohms. Interesting.

Diode measurement works as expected, the standard setting displays the voltage drop across the diode. However by pressing Shift on the meter, you can use the “Auto-diode” function which forward and reverse bias simultaneously using both numeric displays. For example, measuring a 1N4004 diode produces the following display, the forward voltage and the Good/Not good result:

Measuring capacitance is also quite simple, and the manual recommends setting a null value while the probes are open to compensate for residual capacitance. Interestingly the LCD shows when it is charging and discharging the capacitor under test, using the following segments:

Temperature measurement is possible with the included thermocouple and adaptor. Note that the included K-type thermocouple is only rated for up to 200 degrees Celsius, however with an optional unit the meter can measure up to 1372 degrees C. The display can show Fahrenheit as well as Celsius. The meter also shows ambient temperature using the secondary numeric display when it is not in use with other measurement display functions. Finally, measuring AC or DC current is completed as expected, and as noted earlier when switching to another non-current function, the meter will remind you to change the positive lead.

Compared to other meters, there are a few things that irritated me slightly with this unit. The auto-ranging can be somewhat slower than other meters, especially the frequency measurement – it can take around four seconds to measure a constant frequency… my old Tektronix CFC-250 is faster than that. And the exclusion of alligator-clip adaptors and case was disappointing considering the price of the meter. However on a positive note, the meter is supplied with minimal paper documentation, and a full range of manuals, service guides and so on are available for download from the Agilent website.

Update – 14th June 2011

Turns out that many people had similar (and other problems) to myself with their U1272A. They can be solved by updating the firmware via the USB cable. Agilent will send owners of early versions with the affected firmware a free USB cable in order to fix it up. Download this .pdf file with the instructions on how to receive the cable.

Update – 20th June 2011

The USB>DMM cable has arrived and the firmware updated to v2.0. The meter now works as expected – very well. Kudos for Agilent for taking ownership of the problem and sorting it out so rapidly.

Over the last three months I have been using the U1272A and would call it a success. The dual line LCD display really is useful, as well as the low current measurement and especially the Zlow function. There is a short video you can watch that explains a few of the unique features very well. Furthermore, there is a distinct lack of fragility which gives you one less thing to worry about when looking after your tools. Finally there is also the data-logging, however this does require an optional cable. If you are in the market for a full-function electronics multimeter, put this meter on your evaluation list.

High resolution images are available from flickr.

[Disclaimer – the Agilent U1272A in this review is a sample made available by Agilent Technologies via element-14]

Use multiple buttons with one analog input in chapter twenty-five of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe.

[Updated 14/03/2013]

To recap, an analog input pin is connected to an analog to digital (ADC) converter in our Arduino’s microcontroller. It has a ten bit resolution, and can return a numerical value between 0 and 1023 which relates to an analog voltage being read of between 0 and 5 volts DC. With the following sketch:

and in the following short video, we have demonstrated the possible values returned by measuring the voltage from the centre pin of a 10k ohm potentiometer, which is connected between 5V and GND:

As the potentiometer’s resistance decreases, the value returned by analogRead() increases. Therefore at certain resistance values, analogRead() will return certain numerical values. So, if we created a circuit with (for example) five buttons that allowed various voltages to be read by an analog pin, each voltage read would cause analogRead() to return a particular value. And thus we can read the status of a number of buttons using one analog pin. The following circuit is an example of using five buttons on one analog input, using the sketch from example 25.1:

And here it is in action:

Where is the current coming from? Using pinMode(A5, INPUT_PULLUP); turns on the internal pull-up resistor in the microcontroller, which gives us ~4.8V to use. Some of you may have notice that when the right-most button is pressed, there is a direct short between A5 and GND. When that button is depressed, the current flow is less than one milliamp due to the pull-up resistor protecting us from a short circuit. Also note that you don’t have to use A5, any analog pin is fine.

As shown in the previous video clip, the values returned by analogRead() were:

• 1023 for nothing pressed (default state)
• 454 for button one
• 382 for button two
• 291 for button three
• 168 for button four
• 0 for button five

So for our sketches to react to the various button presses, they need to make decisions based on the value returned by analogRead(). Keeping all the resistors at the same value gives us a pretty fair spread between values, however the values can change slightly due to the tolerance of resistors and parasitic resistance in the circuit.

So after making a prototype circuit, you should determine the values for each button, and then have your sketch look at a range of values when reading the analog pin. Doing so becomes more important if you are producing more than one of your project, as resistors of the same value from the same batch can still vary slightly. Using the circuit from example 25.2, we will use a function to read the buttons and return the button number for the sketch to act upon:

And now our video demonstration:

So now you have a useful method for receiving input via buttons without wasting many digital input pins. I hope you found this article useful or at least interesting.

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.

## Tutorial: Arduino and the I2C bus – Part Two

Part two of our Arduino and I2C bus tutorial.

[Updated 28/11/2014]

Today we are going to continue learning about the I2C bus and how it can work for us. If you have not already, please read and understand the first I2C article before continuing.

First of all, there are some limitations of I2C to take into account when designing your projects. One of these is the physical length of the SDA and SCL lines. If all your devices are on the same PCB, then there is nothing to worry about, however if your I2C bus is longer than around one metre, it is recommended that you use an I2C bus extender IC. These ICs reduce electrical noise over the extended-length bus runs and buffer the I2C signals to reduce signal degradation and chance of errors in the data. An example of such an IC is the NXP P82B715 (data sheet). Using a pair of these ICs, you can have cable runs of 20 to 30 metres, using shielded twisted-pair cable. Below is a good example of this, from the aforementioned NXP data sheet:

Several applications come to mind with an extended I2C bus, for example remote temperature monitoring using the the ST Microelectronics CN75 temperature sensor from part one; or controlling several I/O ports using an I2C expander without the expense or worry of using a wireless system. Speaking of which, let’s do that now…

A very useful and inexpensive part is the PCF8574 I/O expander (data sheet.pdf). This gives us another eight outputs, in a very similar method to the 74HC595; or can be used as eight extra inputs. In fact, if you were to use more than one 74HC595 this IC might be preferable, as you can individually address each chip instead of having to readdress every IC in line as you would with shift registers. So how do we do this? First, let’s consult the pinout:

There should not be any surprises for you there. A2~A0 are used to select the last three bits of the device address, P0~P7 are the I/O pins, and INT is an interrupt output which we will not use. To address the PCF8574 we need two things, the device address, and a byte of data which represents the required output pin state. Huh? Consider:

So if we set pins A0 to A2 to GND, our device address in binary will be 0100000, or 0x20 in hexadecimal. And the same again to set the output pins, for example to turn them all on we send binary 0 in hexadecimal which is 0; or to have the first four on and the second four off, use 00001111 which is Ox0F. Hopefully you noticed that those last two values seemed backwards – why would we send a zero to turn all the pins on?

The reason is that the PCF8574 is a current sink. This means that current runs from +5v, through into the I/O pins. For example, an LED would have the anode on the +5V, and the cathode connected to an I/O pin. Normally (for example with a 74HC595) current would run from the IC, through the resistor, LED and then to earth. That is a current source. Consider the following quick diagram:

In the example above, please note that the PCF8574N can take care of current limitation with LEDs, whereas the 74HC595 needs a current-limiting resistor to protect the LED.

Luckily this IC can handle higher volumes of current, so a resistor will not be required. It sounds a bit odd, but like anything is easy once you spend a few moments looking into it. So now let’s use three PCF8574s to control 24 LEDs. To recreate this masterpiece of blinkiness you will need:

• Arduino Uno or compatible board
• Three PCF8574 I/O extenders
• Eight each of red, green and yellow (or your choice) LEDs, each with a current draw of no more than 20mA
• Two 4.7 kilo ohm resistors
• Hook-up wires
• Three 0.1 uF ceramic capacitors

Here is the schematic:

… and the example board layout:

and the example sketch. Note that the device addresses in the sketch match the schematic above. If for some reason you are wiring your PCF8574s differently, you will need to recalculate your device addresses:

And finally our demonstration video:

That was a good example of controlling many outputs with our humble I2C bus. You could literally control hundreds of outputs if necessary – a quite inexpensive way of doing so. Don’t forget to take into account the total current draw of any extended circuits if you are powering from your Arduino boards.

The next devices to examine on our I2C bus ride are EEPROMs – Electrically Erasable Programmable Read-Only Memory. These are memory chips that can store data without requiring power to retain memory. Why would we want to use these? Sometimes you might need to store a lot of reference data for use in calculations during a sketch, such as a mathematical table; or perhaps numerical representations of maps or location data; or create your own interpreter within a sketch that takes instruction from data stored in an array.

In other words, an EEPROM can be used to store data of a more permanent use, ideal for when your main microcontroller doesn’t haven enough memory for you to store the data in the program code. However, EEPROMs are not really designed for random-access or constant read/write operations – they have a finite lifespan. But their use is quite simple, so we can take advantage of them.

EEPROMS, like anything else come in many shapes and sizes. The model we will examine today is the Microchip 24LC256 (data sheet.pdf). It can hold 256 kilobits of data (that’s 32 kilobytes) and is quite inexpensive. This model also has selectable device addresses using three pins, so we can use up to eight at once on the same bus. An example:

The pinouts are very simple:

Pin 7 is “write protect” – set this low for read/write or high for read only. You could also control this in software if necessary. Once again we need to create a slave I2C device address using pins 1, 2 and 3 – these correlate to A2, A1 and A0 in the following table:

So if you were just using one 24LC256, the easiest solution would be to set A0~A2 to GND – which makes your slave address 1010000 or 0x50 in hexadecimal. There are several things to understand when it comes to reading and writing our bytes of data. As this IC has 32 kilobytes of storage, we need to be able to reference each byte in order to read or write to it. There is a slight catch in that you need more than one byte to reference 32767 (as in binary 32767 is 11111111 0100100 [16 bits]).

So when it comes time to send read and write requests, we need to send two bytes down the bus – one representing the higher end of the address (the first 8 bits from left to right), and the next one representing the lower end of the address (the final 8 bits from left to right) – see figure 6.1 on page 9 of the data sheet.

An example – we need to reference byte number 25000. In binary, 25000 is 0110000110101000. So we split that up into 01100001 and 10101000, then covert the binary values to numerical bytes with which to send using the Wire.send(). Thankfully there are two operators to help us with this. This first is >>, known as bitshift right. This will take the higher end of the byte and drop off the lower end, leaving us with the first 8 bits. To isolate the lower end of the address, we use another operator &, known as bitwise and. This unassuming character, when used with 0XFF can separate the lower bits for us. This may seem odd, but will work in the examples below.

Writing data to the 24LC256

Writing data is quite easy. But first remember that a byte of data is 11111111 in binary, or 255 in decimal. First we wake up the I2C bus with:

then send down some data. The first data are the two bytes representing the address (25000) of the byte (12) we want to write to the memory.

And finally, we send the byte of data to store at address 25000, then finish the connection:

There we have it. Now for getting it back…

Reading is quite similar. First we need to start things up and move the pointer to the data we want to read:

Then, ask for the byte(s) of data starting at the current address:

In this example, incomingbyte is a byte variable used to store the data we retrieved from the IC. Now we have the theory, let’s put it into practice with the test circuit below, which contains two 24LC256 EEPROMs. To recreate this you will need:

• Arduino Uno or compatible board
• Two Microchip 24LC256 EEPROMs (you can use 24LC512s as well)
• Two 4.7 kilo ohm resistors
• Hook-up wires
• Two 0.1 uF ceramic capacitors

Here is the schematic:

… the board layout:

and the example sketch. Note that the device addresses in the sketch match the schematic above. If for some reason you are wiring your 24LC256s differently, you will need to recalculate your device addresses. To save time with future coding, we have our own functions for reading and writing bytes to the EEPROM – readData() and writeData(). Consider the sketch for our example:

And the output from the example sketch:

Although the sketch in itself was simple, you now have the functions to read and write byte data to EEPROMS. Now it is up to your imagination to take use of the extra memory.

If you enjoyed this article, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a fourth printing!) “Arduino Workshop”.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column, or join our forum – dedicated to the projects and related items on this website.

## Tutorial: Arduino and the I2C bus – Part One

This is part one of several tutorials on how to use the I2C bus with Arduino, and chapter twenty of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.

[Updated 28/11/2014]

In this first of several tutorials we are going to investigate the I2C data bus, and how we can control devices using it with our Arduino systems. The I2C bus can be a complex interface to master, so I will do my best to simplify it for you. In this article we will learn the necessary theory, and then apply it by controlling a variety of devices. Furthermore it would be in your interest to have an understanding of the binary, binary-coded decimal and hexadecimal number systems.

But first of all, what is it?

I2C is an acronym for “Inter-Integrated Circuit”. In the late 1970s, Philips’ semiconductor division (now NXP) saw the need for simplifying and standardising the data lines that travel between various integrated circuits in their products. Their solution was the I2C bus. This reduced the number of wires to two (SDA – data, and SCL – clock). Here is a nice introductory video from NXP:

Why would we want to use I2C devices?

As there are literally thousands of components that use the I2C interface! And our Arduino boards can control them all. There are many applications, such a real-time clocks, digital potentiometers, temperature sensors, digital compasses, memory chips, FM radio circuits, I/O expanders, LCD controllers, amplifiers, and so on. And you can have more than one on the bus at any time, in fact the maximum number of I2C devices used at any one time is 112.

From a hardware perspective, the wiring is very easy. Those of you with an Arduino Uno or 100% compatible board, you will be using pins A4 for SDA (data) and A5 for SCL (clock):

If you are using an Arduino Mega, SDA is pin 20 and SCL is 21, so note that shields with I2C need to be specifically for the Mega. If you have another type of board, check your data sheet or try the Arduino team’s hardware website.  And finally, if you are using a bare DIP ATmega328-PU microcontroller, you will use pins 27 for SDA and 28 for SCL. The bus wiring is simple:

If you are only using one I2C device, the pull-up resistors are (normally) not required, as the ATmega328 microcontroller in our Arduino has them built-in.  However if you are running a string of devices, use two 10 kilo ohm resistors. Like anything, some testing on a breadboard or prototype circuit will determine their necessity. Sometimes you may see in a particular device’s data sheet the use of different value pull-up resistors – for example 4.7k ohm. If so, heed that advice. The maximum length of an I2C bus is around one metre, and is a function of the capacitance of the bus. This distance can be extended with the use of a special IC, which we will examine during the next I2C chapter.

Each device can be connected to the bus in any order, and devices can be masters or slaves. In our Arduino situation, the board is the master and the devices on the I2C bus are the slaves. We can write data to a device, or read data from a device. By now you should be thinking “how do we differentiate each device on the bus?”… Each device has a unique address. We use that address in the functions described later on to direct our read or write requests to the correct device. It is possible to use two devices with identical addresses on an I2C bus, but that will be discussed in a later article.

As like most devices, we make use of an Arduino library, in this case <wire.h>. Then use the function Wire.begin(); inside of void setup() and we’re ready to go.

Sending data from our Arduino to the I2C devices requires two things: the unique device address (we need this in hexadecimal) and at least one byte of data to send. For example, the address of the part in example 20.1 (below) is 00101111 (binary) which is 0X2F in hexadecimal. Then we want to set the wiper value, which is a value between 0 and 127, or 0x00 and 0x7F in hexadecimal. So to set the wiper to zero, we would use the following three functions:

This sends the device address down the SDA (data) line of the bus. It travels along the bus, and “notifies” the matching device that it has some data coming…

This sends the byte of data to the device – into the device register (or memory of sorts), which is waiting for it with open arms. Any other devices on the bus will ignore this. Note that you can only perform one I2C operation at a time! Then when we have finished sending data to the device, we “end transmission”. This tells the device that we’re finished, and frees up the I2C bus for the next operation:

Some devices may have more than one register, and require more bytes of data in each transmission. For example, the DS1307 real-time clock IC has eight registers to store timing data, each requiring eight bits of data (one byte):

However with the DS1307  – the entire lot need to be rewritten every time. So in this case we would use eight wire.send(); functions every time. Each device will interpret the byte of data sent to it, so you need the data sheet for your device to understand how to use it.

Receiving data from an I2C device into our Arduino requires two things: the unique device address (we need this in hexadecimal) and the number of bytes of data to accept from the device. Receiving data at this point is a two stage process. If you review the table above from the DS1307 data sheet, note that there is eight registers, or bytes of data in there. The first thing we need to do is have the I2C device start reading from the first register, which is done by sending a zero to the device:

Now the I2C device will send data from the first register when requested. We now need to ask the device for the data, and how many bytes we want. For example, if a device held three bytes of data, we would ask for three, and store each byte in its own variable (for example, we have three variables of type byte: a, b, and c. The first function to execute is:

Which tells the device to send three bytes of data back to the Arduino. We then immediately follow this with:

We do not need to use Wire.endTransmission() when reading data. Now that the requested data is in their respective variables, you can treat them like any ordinary byte variable. For a more detailed explanation of the I2C bus, read this explanatory document by NXP. Now let’s use our I2C knowledge by controlling a range of devices…

The Microchip MCP4018T digital linear potentiometer. The value of this model is 10 kilo ohms. Inside this tiny, tiny SMD part is a resistor array consisting of 127 elements and a wiper that we control by sending a value of between 0 and 127 (in hexadecimal) down the I2C bus. This is a volatile digital potentiometer, it forgets the wiper position when the power is removed. However naturally there is a compromise with using such a small part, it is only rated for 2.5 milliamps – but used in conjunction with op amps and so on. For more information, please consult the data sheet. As this is an SMD part, for breadboard prototyping purposes it needed to be mounted on a breakout board. Here it is in raw form:

Above the IC is a breakout board. Consider that the graph paper is 5mm square! It is the incorrect size, but all I have. However soldering was bearable. Put a drop of solder on one pad of the breakout board, then hold the IC with tweezers in one hand, and reheat the solder with the other hand – then push the IC into place. A few more tiny blobs of solder over the remaining pins, and remove the excess with solder wick. Well … it worked for me:

Our example schematic is as follows:

As you can see, the part is simple to use, your signal enters pin 6 and the result of the voltage division is found on pin 5. Please note that this is not a replacement for a typical mechanical potentiometer, we can’t just hook this up as a volume or motor-speed control! Again, please read the data sheet.

Control is very simple, we only need to send one byte of data down, the hexadecimal reference point for the wiper, e.g.:

Here is a quick demonstration that moves the wiper across all points:

and a video demonstration:

Now we will read some data from an I2C device. Our test subject is the ST Microelectronics CN75 temperature sensor. Again, we have another SMD component, but the CN75 is the next stage larger than the part from example 20.1. Thankfully this makes the soldering process much easier, however still requiring some delicate handiwork:

First, a small blob of solder, then slide the IC into it. Once that has cooled, you can complete the rest and solder the header pins into the breakout board:

Our example schematic is as follows:

Pins 5, 6 and 7 determine the final three bits of the device address – in this case they are all set to GND, which sets the address to 1001000. This allows you to use multiple sensors on the same bus. Pin 3 is not used for basic temperature use, however it is an output for the thermostat functions, which we will examine in the next chapter.

As a thermometer it can return temperatures down to the nearest half of a degree Celsius. Although that may not be accurate enough, it was designed for automotive and thermostat use. For more details please read the data sheet. The CN75 stores the temperature data in two bytes, let’s call them A and B. So we use

with the second parameter as 2, as we want two bytes of data. Which we then store using the following functions:

where *a and *b are variables of the type byte. And as always, there is a twist to decoding the temperature from these bytes. Here are two example pieces of sample data: