Controlling motors with an Arduino is a fun and generally integral part of the learning process for most up-and-coming embedded electronics enthusiasts. Or quite simply, using motors is fun ’cause you can make robots, tanks and stuff that moves. And thanks to Freetronics we have their new HBRIDGE motor shield for Arduino to review, so let’s check it out and get some things moving with it.

Arriving in retail-friendly packaging, the HBRIDGE can be stored with the included reusable packaging, and also has a quick-start guide that explains the technical specifications and URLs for tutorials:

The shield is compatible with the latest R3-series Arduino boards including the Leonardo and of course the Freetronics Eleven board:

Specifications

The HBRIDGE shield is based on the Allegro A4954 Dual Full-Bridge DMOS PWM Motor Driver. For the curious, you can download the data sheet (pdf). This allows very simple control of two DC motors with a maximum rating of 40V at 2A, or one bipolar stepper motor. Unlike other motor shields I’ve seen, the HBRIDGE has a jumper which allows the power supply for the motor shield to be fed into the Arduino’s Vin line – so if your motor power supply is under 12V DC you can also power the Arduino from the same supply. Or you can run the motors from the Arduino’s power supply – if you’re sure that you won’t exceed the current rating. Frankly the former would be a safer and this the preferable solution.

The motor(s) are controlled very simply via PWM and digital logic. You feed the A4954 a PWM signal from a digital output pin for motor speed, and also set two inputs with a combination of high/low to set the motor direction, and also put the motor controlled into coast or brake mode. However don’t panic, it’s really easy.

The chassis is pretty much a standard tank chassis with two DC motors that run from an internal 9V battery pack. Search the Internet for “Dagu Rover 5” for something similar. Connection is a simple manner of feeding the power lines from the battery and the motor wires into the terminal block on the HBRIDGE shield.

Next, take note of two things. First – the slide switches below the jumpers. Using these you can select the maximum amount of current allowed to flow from the power supply to each motor. These can be handy to ensure your motor doesn’t burn out by drawing too much current in a stall situation, so you can set these to the appropriate setting for your motor – or if you’re happy there won’t be any issues just leave them both on 2A.

The second thing to note is the six jumpers above the switches. These control which digital pins on your Arduino are used to control the motor driver. Each motor channel requires two outputs and one PWM output. If you leave them all on, the Arduino pins used will be the ones listed next to each jumper, otherwise remove the jumpers and manually wire to the required output. For the purposes of our demonstration, we’ll leave all the jumpers in. A final word of warning is to be careful not to touch the A4954 controller IC after some use – it can become really hot … around 160 degrees Celsius. It’s the circled part in the image below:

So back to the DC motors. You have two digital outputs to set, and also a PWM signal to generate – for each channel. If you set the outputs to 1 and 0 – the motor spins in one direction. Use 0 and 1 to spin the other way. And the value of the PWM (0~255) determines the speed. So consider the following sketch:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

// Freetronics HBridge shield demonstration

intmotora1=4;

intmotora2=7;

intmotoraspeed=6;

intmotorb1=3;

intmotorb2=2;

intmotorbspeed=5;

voidsetup()

{

pinMode(motora1,OUTPUT);

pinMode(motora2,OUTPUT);

pinMode(motoraspeed,OUTPUT);

pinMode(motorb1,OUTPUT);

pinMode(motorb2,OUTPUT);

pinMode(motorbspeed,OUTPUT);

delay(5000);

}

voidallOff()

// turns both motors off

{

digitalWrite(motora1,LOW);

digitalWrite(motora2,LOW);

digitalWrite(motoraspeed,LOW);

digitalWrite(motorb1,LOW);

digitalWrite(motorb2,LOW);

digitalWrite(motorbspeed,LOW);

}

voidgoForward(intspeed)

{

digitalWrite(motora1,HIGH);

digitalWrite(motora2,LOW);

digitalWrite(motoraspeed,speed);

digitalWrite(motorb1,HIGH);

digitalWrite(motorb2,LOW);

digitalWrite(motorbspeed,speed);

}

voidgoBackward(intspeed)

{

digitalWrite(motora1,LOW);

digitalWrite(motora2,HIGH);

digitalWrite(motoraspeed,speed);

digitalWrite(motorb1,LOW);

digitalWrite(motorb2,HIGH);

digitalWrite(motorbspeed,speed);

}

voidturnRight(intspeed)

{

digitalWrite(motora1,LOW);

digitalWrite(motora2,HIGH);

digitalWrite(motoraspeed,speed);

digitalWrite(motorb1,HIGH);

digitalWrite(motorb2,LOW);

digitalWrite(motorbspeed,speed);

}

voidturnLeft(intspeed)

{

digitalWrite(motora1,HIGH);

digitalWrite(motora2,LOW);

digitalWrite(motoraspeed,speed);

digitalWrite(motorb1,LOW);

digitalWrite(motorb2,HIGH);

digitalWrite(motorbspeed,speed);

}

voidloop()

{

goForward(255);

delay(1000);

turnLeft(200);

delay(1000);

goBackward(255);

delay(1000);

turnRight(200);

delay(1000);

}

Instead of chasing the tank chassis with a camera, here it is on the bench:

Now to try out a stepper motor. You can control a bipolar motor with the HBRIDGE shield, and each coil (pole) is connected to a motor channel.

Hint – if you’re looking for a cheap source of stepper motors, check out discarded office equipment such as printers or photocopiers.

For the demonstration, I’ve found a random stepper motor from a second-hand store and wired up each pole to a channel on the HBRIDGE shield – then run the Arduino stepper motor demonstration sketch by Tom Igoe:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

/*

Based on example by Tom Igoe included in Arduino IDE

at File -> Examples -> Stepper -> stepper_oneRevolution

Modified to suit pinouts of Freetronics HBridge Shield

*/

#include <Stepper.h>

constintstepsPerRevolution=240;// change this to fit the number of steps per revolution

// for your motor

// initialize the stepper library using the default pins on the HBridge Shield:

SteppermyStepper(stepsPerRevolution,4,7,3,2);

voidsetup(){

// set the speed at 200 rpm:

myStepper.setSpeed(200);

// initialize the serial port:

Serial.begin(38400);

}

voidloop(){

// step one revolution in one direction:

Serial.println("clockwise");

myStepper.step(stepsPerRevolution);

delay(1000);

// step one revolution in the other direction:

Serial.println("counterclockwise");

myStepper.step(-stepsPerRevolution);

delay(1000);

}

With the following results:

Considering it was a random stepper motor for which we didn’t have the specifications for – it’s always nice to have it work the first time! For more formal situations, ensure your stepper motor matches the power supply voltage and so on. Nevertheless it shows how easy it can be to control something that appears complex to some people, so enjoy experimenting with them if you can.

Competition

Thanks to Freetronics we have a shield to give away to one lucky participant. To enter, clearly print your email address on the back of a postcard and mail it to:

H-Bridge Competition, PO Box 5435 Clayton 3168 Australia.

Entries must be received by the 20th of September 2013. One postcard will then be drawn at random, and the winner will receive one H-Bridge shield delivered by Australia Post standard air mail. One entry per person – duplicates will be destroyed. We’re not responsible for customs or import duties, VAT, GST, import duty, postage delays, non-delivery or whatever walls your country puts up against receiving inbound mail.

Conclusion

As demonstrated, the HBRIDGE shield “just works” – which is what you need when bringing motorised project ideas to life. The ability to limit current flow and also power the host board from the external supply is a great idea, and with the extra prototyping space on the shield you can also add extra circuitry without needing another protoshield. Very well done. For more information and to order, visit the Freetronics website. Full-sized images are on flickr. 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 twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.

Note – The motor shield used in this article was a promotional consideration supplied by Freetronics.

Recently the Arduino Leonardo was released, and I’ve finally got my hands on one. Some have claimed that the Leonardo as the successor to the Arduino Uno board, however that is somewhat subjective. In this article we have a look for ourselves and examine the differences between the Uno boards that we’re used to and the new Leonardo.

The board

Here it is unwrapped from the cardboard packet:

It uses the same physical footprint as the Uno, so no surprises there:

Now to travel around the board and see what’s new. First is the microcontroller – we have the Atmel ATmega32U4:

There are several pros and cons to using the 32U4. The pros include:

More analogue inputs. As well as the usual A0~A5, digital pins 4,6,8,9,10 and 12 can be configured as A6~A11

It handles USB. So no more external USB controller MCU or the old FTDI chip. Supposedly this saves money, however the retail price in some markets don’t reflect this

More PWM pins – well one more. They’re now on D3, 5, 6, 9, 10, 11 and 13

There is a little more SRAM than the Uno, it is now 2.5 kB

SPI has moved – they’re now wired to the ICSP pins. So you now have D10~D13 seperate to SPI

And the cons:

SPI has moved – they’re now wired to the ICSP pins. So if you have any shields that use SPI – too bad, they’re out. The most common example of this will be Ethernet shields – you’ll need to modify them with some jumper leads to contact the ICSP pins

I2C has moved over to D2+3. So if you have any shields using I2C – they’ll need to be modified

Less flash memory – the bootloader uses 4 kB of the 32 kB flash (the Uno used 0.5 kB)

However you can get an adaptor shield to use older Arduino shields with the Leonardo.

For MCU to Arduino pin mapping, see here. Next, for more on the USB side of things – as the 32U4 takes care of USB – take heed of the following notes from arduino.cc:

Since the Leonardo does not have a dedicated chip to handle serial communication, it means that the serial port is virtual— it’s a software routine, both on your operating system, and on the Leonardo itself. Just as your computer creates an instance of the serial port driver when you plug in any Arduino, the Leonardo creates a serial instance whenever it runs its bootloader. The Leonardo is an instance of USB’s Connected Device Class (CDC) driver.

This means that every time you reset the board, the Leonardo’s USB serial connection will be broken and re-established. The Leonardo will disappear from the list of serial ports, and the list will re-enumerate. Any program that has an open serial connection to the Leonardo will lose its connection. This is in contrast to the Arduino Uno, with which you can reset the main processor (the ATmega328P) without closing the USB connection (which is maintained by the secondaryATmega8U2 or ATmega16U2 processor).

There are some other changes to the board. Moving on, the next change is the USB socket. Do you recognise this socket?

Yes – micro USB. Thankfully (!) a growing number of mobile phones use this type for charging and USB connection, so you may already have a matching cable. Note that the Leonardo doesn’t include a cable, so if you’re an iPhone user – order yourself a cable with your Leonardo.

Next, the LEDs have been moved to the edge of the board. You can see them in the above image to the right of the USB socket. No more squinting through shields at strange angles to check the TX/RX lights. However this isn’t a new invention, our friends at Freetronics have been doing this for some time. Furthermore, the reset button has been moved to the corner for easier access.

There are also seperate connectors for the I2C bus – next to AREF, which should make modifying existing shields a little easier:

Finally, due to the reduction in components and shift to SMD – there is what could almost be called a large waste of space on the board:

A few extra user LEDs wouldn’t have been a bad idea, or perhaps circuitry to support Li-Po rechargeable batteries. However the argument will be “that’s what a protoshield is for”. Just saying… As for the rest of the hardware, the specifications can be found here.

Finally, the Leonardo is available in two versions – with and without headers. This makes it easier to embed the Leonardo into fixed applications as you can directly solder to the various I/O pins. An alternative to this would instead be the Freetronics LeoStick, as it is much smaller yet fully compatible.

Software

First – you need to drag yourself into Arduino IDE v1.0.1. Note you can run more than one version of the IDE on the same machine if you don’t mind sharing the same preferences file. Next, the Leonardo doesn’t reset when you open the serial monitor window (from arduino.cc) –

That means you won’t see serial data that’s already been sent to the computer by the board, including, for example, most data sent in the setup() function. This change means that if you’re using any Serial print(), println() or write() statments in your setup, they won’t show up when you open the serial monitor. To work around this, you can check to see if the serial port is open like so:

Arduino

1

2

// while the serial stream is not open, do nothing:

while(!Serial);

Using the 32U4, you also have two serial ports. The first is the emulated one via the USB, and the second is the hardware UART on digital pins 0 and 1. Furthermore, the Leonardo can emulate a USB keyboard and mouse – however with a few caveats. There is a section on the Leonardo homepage that you should really read and take note of. But this emulation does sound interesting, and we look forward to developing some interesting tools to take use of them, so stay tuned.

Conclusion

There is nothing wrong with the Leonardo board, it works as described. However you could consider this a virtual “line in the sand”, or a new beginning. Due to the changes in the pinouts shields will need to be redesigned, and for those of you still programming in Arduino v23 – it’s time to get up to speed with v1.0.1. If you need the special USB functions, keyboard and/or mouse emulation, or are happy with the changes and can get one for less than the cost of a Uno – great.

Here’s a video from the main man Massimo Banzi:

However if you’re looking for your first Arduino board – this isn’t the board for you right now. There are too many incompatible shields out there, and the inability to cheaply replace the microcontroller will see some beginners burn out their first couple of boards rendering them useless. Get yourself an Arduino Uno or compatible board such as the Freetronics Eleven.

In conclusion, classifying the Leonardo board as good or bad is not a simple decision. It may or may not be an improvement – depending on your needs. Right now – for beginners, this is not the board for you. For those who understand the differences between a Uno and Leonardo, sure – no problem. Frankly, I would get a LeoStick instead. At the end – it’s up to you to make an informed decision.

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

In this article we examine another style of vintage display technology – the incandescent seven-segment digital display. We are using the FFD51 by the IEE company (data sheet.pdf) – dating back to the early 1970s. Here is a close-up of our example:

You can see the filaments for each of the segments, as well as the small coiled ‘decimal point’ filament at the top-right of the image above. This model has pins in a typical DIP format, making use in a solderless breadboard or integration into a PCB very simple:

It operates in a similar manner to a normal light bulb – the filaments are in a vacuum, and when a current is applied the filament glows nicely. The benefit of using such as display is their brightness – they could be read in direct sunlight, as well as looking good inside. At five volts each segment draws around 30mA. For demonstration purposes I have been running them at a lower voltage (3.5~4V), as they are old and I don’t want to accidentally burn out any of the elements.

Using these with an Arduino is very easy as they segments can be driven from a 74HC595 shift register using logic from Arduino digital out pins. (If you are unfamiliar with doing so, please read chapters four and five of my tutorial series). For my first round of experimenting, a solderless breadboard was used, along with the usual Freetronics board and some shift register modules:

Although the modules are larger than a DIP 74HC595, I like to use these instead. Once you solder in the header pins they are easier to insert and remove from breadboards, have the pinouts labelled clearly, are almost impossible to physically damage, have a 100nF capacitor for smoothing and a nice blue LED indicating power is applied.

Moving forward – using four shift register modules and displays, a simple four-digit circuit can be created. Note from the datasheet that all the common pins need to be connected together to GND. Otherwise you can just connect the outputs from the shift register (Q0~Q7) directly to the display’s a~dp pins.

Some of you may be thinking “Oh at 30mA a pin, you’re exceeding the limits of the 74HC595!”… well yes, we are. However after several hours they still worked fine and without any heat build-up. However if you displayed all eight segments continuously there may be some issues. So take care. As mentioned earlier we ran the displays at a lower voltage (3.5~4V) and they still displayed nicely. Furthermore at the lower voltage the entire circuit including the Arduino-compatible board used less than 730mA with all segments on – for example:

For the non-believers, here is the circuit in action:

Here is the Arduino sketch for the demonstration above:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

// IED FF1 incandescent display demonstration

// using four displays connected to four 74HC595s

intclockPin=7;

intlatchPin=8;

intdataPin=9;

intdd=400;

// array for anodes (to display 0~9)

// the bits represent segments a~dp from left to right

// if you add one to the number (or turn on the last bit) the decimal point turns on

Now for the prototype of something more useful – another clock. 🙂 Time to once again pull out my Arduino-compatible board with onboard DS1307 real-time clock. For more information on the RTC IC and getting time data with an Arduino please visit chapter twenty of my tutorials. For this example we will use the first two digits for the hours, and the last two digits for minutes. The display will then rotate to showing the numerical day and month of the year – then repeat.

Operation is simple – just get the time from the DS1307, then place the four digits in an array. The elements of the array are then sent in reverse order to the shift registers. The procedure is repeated for the date. Anyhow, here is the sketch:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

#include "Wire.h"

#define DS1307_I2C_ADDRESS 0x68

// note the digital pins of the arduino that are connected to the nixie driver

intclockPin=7;

intlatchPin=8;

intdataPin=9;

intclockArray[5];// holds the digits to display

inta=0;

// the bits represent segments a~dp from left to right

// if you add one to the number (or turn on the last bit) the decimal point turns on

shiftOut(dataPin,clockPin,LSBFIRST,numbers[clockArray[2]]+1);// digit 2 and decimal point

shiftOut(dataPin,clockPin,LSBFIRST,numbers[clockArray[1]]);// digit 1

digitalWrite(latchPin,HIGH);

}

voidloop()

{

showTime();// display the time

delay(5000);

showDate();// display the date (day and month) for two seconds

delay(2000);

}

and the clock in action:

So there you have it – another older style of technology dragged into the 21st century. If you enjoyed this article you may also like to read about vintage HP LED displays. Once again, I hope you found this article of interest. Thanks to the Vintage Technology Association website for background information.

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

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:

Arduino

1

start=millis();

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

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

/*

Example 37.1 - millis() demonstration

http://tronixstuff.com/tutorials > chapter 37

John Boxall | CC by-sa-nc

*/

unsignedlongstart,finished,elapsed;

voidsetup()

{

Serial.begin(9600);

}

voidloop()

{

Serial.println("Start...");

start=millis();

delay(1000);

finished=millis();

Serial.println("Finished");

elapsed=finished-start;

Serial.print(elapsed);

Serial.println(" milliseconds elapsed");

Serial.println();

delay(500);

}

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:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

/*

Example 37.2 – Super-basic stopwatch using millis();

http://tronixstuff.com/tutorials > chapter 37

John Boxall | CC by-sa-nc

*/

unsignedlongstart,finished,elapsed;

voidsetup()

{

Serial.begin(9600);

pinMode(2,INPUT);// start button

pinMode(3,INPUT);// stop button

Serial.println("Press 1 for Start/reset, 2 for elapsed time");

}

voiddisplayResult()

{

floath,m,s,ms;

unsignedlongover;

elapsed=finished-start;

h=int(elapsed/3600000);

over=elapsed%3600000;

m=int(over/60000);

over=over%60000;

s=int(over/1000);

ms=over%1000;

Serial.print("Raw elapsed time: ");

Serial.println(elapsed);

Serial.print("Elapsed time: ");

Serial.print(h,0);

Serial.print("h ");

Serial.print(m,0);

Serial.print("m ");

Serial.print(s,0);

Serial.print("s ");

Serial.print(ms,0);

Serial.println("ms");

Serial.println();

}

voidloop()

{

if(digitalRead(2)==HIGH)

{

start=millis();

delay(200);// for debounce

Serial.println("Started...");

}

if(digitalRead(3)==HIGH)

{

finished=millis();

delay(200);// for debounce

displayResult();

}

}

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:

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.

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

Arduino

1

floatcircMetric=1.2;

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 twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.

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:

// our MCP4162s requires data to be sent MSB (most significant byte) first

}

voidsetValue(intl,intvalue)

// sends value 'value' to SPI device on CS digital out pin 'l'

{

digitalWrite(l,LOW);

SPI.transfer(0);// send command byte

SPI.transfer(value);// send value (0~255)

digitalWrite(l,HIGH);

}

voidallOff()

// sets all pots to max resistance

{

setValue(led1,255);

setValue(led2,255);

setValue(led3,255);

setValue(led4,255);

}

voidpulse(intl)

{

allOff();

for(inta=255;a>=0;--a)

{

setValue(l,a);

delay(del);

}

for(inta=0;a<256;a++)

{

setValue(l,a);

delay(del);

}

}

voidpulseAll()

{

allOff();

for(inta=255;a>=0;--a)

{

setValue(led1,a);

setValue(led2,a);

setValue(led3,a);

setValue(led4,a);

delay(del);

}

for(inta=0;a<256;a++)

{

setValue(led1,a);

setValue(led2,a);

setValue(led3,a);

setValue(led4,a);

delay(del);

}

}

voidloop()

{

pulse(led1);

pulse(led2);

pulse(led3);

pulse(led4);

pulseAll();

}

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

Arduino

1

voidsetValue(intl,intvalue)

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:

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.

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:

Arduino

1

2

3

4

digitalWrite(10,LOW);// select the DS3234 that has its CS line on digital 10

SPI.transfer(0x08);// tell the DS3234 device we're requesting data from the register at 08h

data=SPI.transfer(0);// the DS3234 sends the data back and stores it in the byte data

digitalWrite(10,HIGH);// deselect the DS3234 if finished with it

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:

Arduino

1

2

3

4

digitalWrite(10,LOW);

SPI.transfer(0x80);// tells the device which address to write to

SPI.transfer(b00001010);// you can send any representation of a byte

digitalWrite(10,HIGH);

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:

Arduino

1

SPI.setDataMode(SPI_MODE1);

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 twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.

How long does the internal EEPROM of an Atmel ATmega328 last for? Let’s find out…

Updated 18/03/2013

Some time ago I published a short tutorial concerning the use of the internal EEPROM belonging to the Atmel ATmega328 (etc.) microcontroller in our various Arduino boards. Although making use of the EEPROM is certainly useful, it has a theoretical finite lifespan – according to the Atmel data sheet (download .pdf) it is 100,000 write/erase cycles.

One of my twitter followers asked me “is that 100,000 uses per address, or the entire EEPROM?” – a very good question. So in the name of wanton destruction I have devised a simple way to answer the question of EEPROM lifespan. Inspired by the Dangerous Prototypes’ Flash Destroyer, we will write the number 170 (10101010 in binary) to each EEPROM address, then read each EEPROM address to check the stored number. The process is then repeated by writing the number 85 (01010101 in binary) to each address and then checking it again. The two binary numbers were chosen to ensure each bit in an address has an equal number of state changes.

After both of the processes listed above has completed, then the whole lot repeats. The process is halted when an incorrectly stored number is read from the EEPROM – the first failure. At this point the number of cycles, start and end time data are shown on the LCD.

In this example one cycle is 1024 sequential writes then reads. One would consider the entire EEPROM to be unusable after one false read, as it would be almost impossible to keep track of individual damaged EEPROM addresses. (Then again, a sketch could run a write/read check before attempting to allocate data to the EEPROM…)

If for some reason you would like to run this process yourself, please do not do so using an Arduino Mega, or another board that has a fixed microcontroller. (Unless for some reason you are the paranoid type and need to delete some data permanently). Once again, please note that the purpose of this sketch is to basically destroy your Arduino’s EEPROM. Here is the sketch:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

/*

Arduino EEPROM killer

John Boxall - http://tronixstuff.com - May 2011

CC by-sa

Note: This sketch will destroy your Arduino's EEPROM

Do not use with Arduino boards that have non-replaceable microcontrollers

Sketch assumes DS1307 already contains current date and time

*/

#include <EEPROM.h>

#include <LiquidCrystal.h>

LiquidCrystallcd(4,5,6,7,8,9);

#include "Wire.h"

#define DS1307_I2C_ADDRESS 0x68

// all these bytes necessary for time and date data

bytesecond,minute,hour,dayOfWeek,dayOfMonth,month,year;

bytesday,smonth,ssecond,sminute,shour;

bytefday,fmonth,fsecond,fminute,fhour;

// to store number of cycles. Should be enough

longcycles=0;// maximum size is 2,147,483,647

intzz=0;

voidsetup()

{

lcd.begin(16,2);// fire up the LCD

Wire.begin();// and the I2C bus

}

// Convert normal decimal numbers to binary coded decimal

bytedecToBcd(byteval)

{

return((val/10*16)+(val%10));

}

// Convert binary coded decimal to normal decimal numbers

bytebcdToDec(byteval)

{

return((val/16*10)+(val%16));

}

// Gets the date and time from the ds1307

voidgetDateDs1307(byte*second,

byte*minute,

byte*hour,

byte*dayOfWeek,

byte*dayOfMonth,

byte*month,

byte*year)

{

// Reset the register pointer

Wire.beginTransmission(DS1307_I2C_ADDRESS);

Wire.write(0);

Wire.endTransmission();

Wire.requestFrom(DS1307_I2C_ADDRESS,7);

// A few of these need masks because certain bits are control bits

*second=bcdToDec(Wire.read()&0x7f);

*minute=bcdToDec(Wire.read());

*hour=bcdToDec(Wire.read()&0x3f);// Need to change this if 12 hour am/pm

If you are unfamiliar with the time-keeping section, please see part one of my Arduino+I2C tutorial. The LCD used was my quickie LCD shield – more information about that here. Or you could always just send the data to the serial monitor box – however you would need to leave the PC on for a loooooong time… So instead the example sat on top of an AC adaptor (wall wart) behind a couch (sofa) for a couple of months:

The only catch with running it from AC was the risk of possible power outages. We had one planned outage when our house PV system was installed, so I took a count reading before the mains was turned off, and corrected the sketch before starting it up again after the power cut. Nevertheless, here is a short video – showing the start and the final results of the test:

So there we have it, 1230163 cycles with each cycle writing and reading each individual EEPROM address. If repeating this odd experiment, your result will vary.

Well I hope someone out there found this interesting. Please refrain from sending emails or comments criticising the waste of a microcontroller – this was a one off.

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

Today we are going to examine the internal EEPROM in our Arduino boards. What is an EEPROM some of you may be saying? An EEPROM is an Electrically Erasable Programmable Read-Only Memory. It is a form of non-volatile memory that can remember things with the power being turned off, or after resetting the Arduino. The beauty of this kind of memory is that we can store data generated within a sketch on a more permanent basis.

Why would you use the internal EEPROM? For situations where data that is unique to a situation needs a more permanent home. For example, storing the unique serial number and manufacturing date of a commercial Arduino-based project – a function of the sketch could display the serial number on an LCD, or the data could be read by uploading a ‘service sketch’. Or you may need to count certain events and not allow the user to reset them – such as an odometer or operation cycle-counter.

What sort of data can be stored? Anything that can be represented as bytes of data. One byte of data is made up of eight bits of data. A bit can be either on (value 1) or off (value 0), and are perfect for representing numbers in binary form. In other words, a binary number can only uses zeros and ones to represent a value. Thus binary is also known as “base-2″, as it can only use two digits.

How can a binary number with only the use of two digits represent a larger number? It uses a lot of ones and zeros. Let’s examine a binary number, say 10101010. As this is a base-2 number, each digit represents 2 to the power of x, from x=0 onwards:

See how each digit of the binary number can represent a base-10 number. So the binary number above represents 85 in base-10 – the value 85 is the sum of the base-10 values. Another example – 11111111 in binary equals 255 in base 10.

Now each digit in that binary number uses one ‘bit’ of memory, and eight bits make a byte. Due to internal limitations of the microcontrollers in our Arduino boards, we can only store 8-bit numbers (one byte) in the EEPROM. This limits the decimal value of the number to fall between zero and 255. It is then up to you to decide how your data can be represented with that number range. Don’t let that put you off – numbers arranged in the correct way can represent almost anything!

There is one limitation to take heed of – the number of times we can read or write to the EEPROM. According to the manufacturer Atmel, the EEPROM is good for 100,000 read/write cycles (see the data sheet). One would suspect this to be a conservative estimate, however you should plan accordingly. *Update* After some experimentation, the life proved to be a lot longer…

Now we know our bits and and bytes, how many bytes can be store in our Arduino’s microcontroller? The answer varies depending on the model of microcontroller. For example:

Boards with an Atmel ATmega1280 or 2560, such as the Arduino Mega series – 4096 bytes (4 kilobytes)

Boards with an Atmel ATmega168, such as the original Arduino Lilypad, old Nano, Diecimila etc – 512 bytes.

If y0u are unsure have a look at the Arduino hardware index or ask your board supplier.

If you need more EEPROM storage than what is available with your microcontroller, consider using an external I2C EEPROM as described in the Arduino and I2C tutorial part two.

At this point we now understand what sort of data and how much can be stored in our Arduino’s EEPROM. Now it is time to put this into action. As discussed earlier, there is a finite amount of space for our data. In the following examples, we will use a typical Arduino board with the ATmega328 with 1024 bytes of EEPROM storage.

To use the EEPROM, a library is required, so use the following library in your sketches:

Arduino

1

#include "EEPROM.h"

The rest is very simple. To store a piece of data, we use the following function:

Arduino

1

EEPROM.write(a,b);

The parameter a is the position in the EEPROM to store the integer (0~255) of data b. In this example, we have 1024 bytes of memory storage, so the value of a is between 0 and 1023. To retrieve a piece of data is equally as simple, use:

Arduino

1

z=EEPROM.read(a);

Where z is an integer to store the data from the EEPROM position a. Now to see an example.

This sketch will create random numbers between 0 and 255, store them in the EEPROM, then retrieve and display them on the serial monitor. The variable EEsize is the upper limit of your EEPROM size, so (for example) this would be 1024 for an Arduino Uno, or 4096 for a Mega.

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

// Example 31.1 - Arduino internal EEPROM demonstration

#include <EEPROM.h>

intzz;

intEEsize=1024;// size in bytes of your board's EEPROM

voidsetup()

{

Serial.begin(9600);

randomSeed(analogRead(0));

}

voidloop()

{

Serial.println("Writing random numbers...");

for(inti=0;i<EEsize;i++)

{

zz=random(255);

EEPROM.write(i,zz);

}

Serial.println();

for(inta=0;a<EEsize;a++)

{

zz=EEPROM.read(a);

Serial.print("EEPROM position: ");

Serial.print(a);

Serial.print(" contains ");

Serial.println(zz);

delay(25);

}

}

The output from the serial monitor will appear as such:

So there you have it, another useful way to store data with our Arduino systems. Although not the most exciting tutorial, it is certainly a useful.

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

In this article we will learn how to send messages from our Arduino to twitter. For the uninitiated who may be thinking “what is all this twitter nonsense about?”, twitter is a form of microblogging. You can create a message with a maximum length of 140 characters, and broadcast this on the twitter service. For people to receive your messages (or tweets) they also need to be a member of twitter and choose to subscribe to your tweets.

Generally people will use the twitter service using one of three methods: using a web browser on a personal computer or internet device, on a mobile phone, or using a specific application such as TweetDeck on one of the aforementioned devices. For example, here is a typical web browser view:

And here is an example of a twitter application running on an Android OS smartphone:

So as you can see, it is easy enough to read peoples’ tweets. Therein lies the reason for this article – we can harness twitter as an output device for our Arduino systems. We can broadcast various messages, so systems can be created to monitor specific parameters and report on their status at regular intervals, upon an event occurring, and so on.

In some areas, you can set twitter to send tweets from a certain user to your mobile phone via SMS – however if doing so be careful to confirm possible charges to your mobile phone account. Finally, if you are worried about privacy with regards to your tweets, you can set your account to private and only allow certain people to follow your tweets.

So let’s get started. First of all – you will need a twitter account. If you do not have one, you can sign up for one here. If you already have a twitter account, you can always open more for other uses – such as an Arduino. For example, my twitter account is @tronixstuff, but my demonstration machine twitter account is @tronixstuff2. Then I have set my primary account to follow my machine’s twitter account. Once you have logged into twitter with your machine account, visit this page and get yourself a token by following the Step One link. Save your token somewhere safe, you’ll need to insert it into your Arduino sketch.

Next, you will need some hardware. Apart from your usual Arduino board, you will need an Ethernet shield. However to save space and money I’ll be using the Freetronics EtherTen:

If you are unfamiliar with using Arduino and Ethernet, please review chapter sixteen before continuing forward with this article. From a software perspective, we will need another library for our Arduino IDE. Download and install the twitter library from here. Now, at this point – please run the Webserver example described in chapter sixteen and ensure it is working before moving forward from this point. While you do that, we’ll have a break…

Now it is time to send our first tweet. The following sketch is a modification of the demonstration version, in which we have isolated the tweet-sending into a separate function called (strangely enough) tweet();. It is not complex at all:

So after uploading the above sketch, running a network cable from your access point to the Ethernet shield, and powering up the Arduino board – your tweet should appear as such:

Excellent – it works. And I hope yours did as well. If it did not, open the serial monitor box to get some feedback from the sketch. From experimentation the most amount of errors are caused by incorrect IP and trying to send multiple tweets too quickly. If you get excited and try to run the sketch again by hitting reset, twitter will reply back with an error – it does not allow duplicate tweets to be sent (over a short period of time). Twitter will reply to your tweet with a code which describes the result of your tweet. This code is stored in an integer variable using the function:

Arduino

1

intstatus=twitter.wait(&Serial);

For example, 200 means the tweet was sent successfully, and 403 means you have attempted a duplicate tweet. However you can omit the code-checking if you are not fussed about your tweet’s status.

Although it was fun tweeting Hello world, let’s create an example that reacts to various events and tweets about them. To simulate some events I have connected four buttons to digital inputs (using the button board from chapter twelve). Pressing a button sends of the matching message. However you can use any form of digital output or decision-making in your sketch. For now, here is the example sketch:

And here is a screen shot of the results after pressing buttons one, four, two then three:

So there you have it, another useful way to send information from your Arduino to the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Big thanks to @neocat for their work with the twitter Arduino libraries.

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

Within this article we are going to examine another new kit available from Freetronics, a company formed to provide many interesting Arduino-based products after the publication of the book “Practical Arduino” by Jonathan Oxer and Hugh Blemings – which in itself is a good read, there are many interesting projects to make and learn from.

Today we examine their answer to “is there a kit version of the TwentyTen Arduino Duemilanove-compatible board?” – by assembling their KitTen. Some people may be wondering why one would want to build a KitTen instead of an assembled unit. Personally I could think of the following reasons:

It’s fun to make something and see it work;

You can save over Au$10;

There are a lot more smoothing capacitors in the KitTen design than normal boards;

There is a dedicated 3.3V 100 milliamp power regulator (twice the current of the usual board’s 50mA supply) – ideal for running thirsty shields that need a native 3.3V;

The board is for a project that needs to use a modified version of the TwentyTen/Duemilanove;

You want a board with a native serial instead of USB interface;

All that lovely prototyping area above the microcontroller;

The power light and LED for D13 are always visible due to their location on the edge of the PCB;

You could solder in your microcontroller to avoid theft – great for school and public use (Yes, this has happened)…

And so on. Moving forward, opening the KitTen package reveals the following:

Once again with a Freetronics kit, all instructions are included in colour, as well as the circuit schematic and another sheet explaining how the KitTen will work with Arduino systems and the specifications. The PCB is solder-masked and silk-screened with a very informative layout:

The rest of the included components shipped in an anti-static bag, including labelled resistors and an IC socket for the microcontroller:

By following the included detailed instructions, everything went well. The layout on the PCB is detailed with all component values, which makes life easier. Starting with the low-profile components:

… followed by higher-profile components such as the IC socket and capacitors:

… and finally the shield sockets. Instead of trying to balance them, it is a lot quicker to place the sockets on an existing Arduino shield, turn it over, drop the KitTen on top then solder the pins in:

Then finally we are finished:

There are a couple of things to watch out for when using your KitTen. The first is to make sure you have the power-select jumper fitted correctly:

Place it on the left pins (as above) to power your KitTen from the FTDI cable; place the jumper on the right pins to power from the DC socket. You should use a power supply of between 9 to 12 volts DC at one amp. The second item to take care with is the blue power LED. The supplied model was so bright it was like staring into the sun. You may wish to test your own one and possibly replace it for a duller version, or use some fine sandpaper to reduce the brightness of the included LED. To upload sketches to your KitTen you will need a 5 volt FTDI cable. As mentioned above, this can also power your board as well.

Overall, this is an excellent kit, and considering the price of doing it yourself – good value as well. To get your hands on this product– visit Freetronics’ website, or your local reseller.

Remember, if you have any questions about these modules please contact Freetronics via their website.

Today we examine their latest kit, the “16×2 LCD Arduino Shield“. This is a very easy to construct, yet useful tool for those experimenting, prototyping and generally making things with their Arduino-based systems. The purpose of the shield is to offer easy access to a 16 x 2 character LCD module, and also the use of five buttons – connected to an analog input using the resistor ladder method. The kit comes packaged very well, and includes not only detailed printed instructions in colour, but also the full circuit schematic:

It is nice to see such a high level of documentation, even though most people may not need it – there is generally someone who does. Sparkfun – get the hint. All the parts are included, and for the first time in my life the resistors were labelled as well:

So being Mr Pedantic I followed the instructions, and happily had the components in without any troubles. The next step was the Arduino shield pins – the best way to solder these is to insert into your Arduino board, drop the shield on top then solder away as such:

And finally, bolting on the LCD whilst keeping the header pins for the LCD in line. Some people may find the bolt closest to D0 interferes with the shield pin, so you can insert the bolt upside down as I have. Remember to not solder the LCD pins until you are happy it is seated in correctly:

Once you are satisfied the pins are lined up and sitting in their required position – solder them in, tighten your nuts and that’s it:

The contrast of the LCD in real life is better than shown in the photo above – photographing them is a little difficult for me. However once assembled, using the shield is quite easy. If your LCD doesn’t seem to be working after your first sketch, adjust the contrast using the potentiometer. The LCD is a standard HD44780-interface model, and wired in to use a 4-bit parallel data interface. If using these types of LCD is new to you, perhaps visit this article then return. Our shield uses the pins: A0 and D4~D9.

One uses the standard Arduino liquidCrystal library with this LCD, and the function parameters to use are as follows:

LiquidCrystal lcd(8,9,4,5,6,7)

The buttons are read using analog pin A0. Use the following sketch to find the values returned by the analogRead function:

Now that we know the values returned for each button, we can take advantage of them to create, for example, a type of menu system – or some sort of controller. In the second example, we have used a modified TwentyTen with a DS1307 real-time clock IC to make a digital clock. The buttons on the LCD shield are utilised to create a user-friendly menu to set the clock time.

In general this is an excellent kit, and considering the price of doing it yourself – good value as well. To get your hands on this product in kit or assembled form – visit Freetronics’ website, or your local reseller.

Remember, if you have any questions about these modules please contact Freetronics via their website. Higher resolution images available on flickr.

[Note – the kit assembled in this article was received from Freetronics for review purposes]

Now and again I find myself making another kind of clock or timing device using the Arduino system, and each one has been making use of the Maxim DS1307 real-time clock IC. However every time another clock is being worked on, my DS1307 real-time clock shield needs to come out to play. Although in itself it is a nice shield, at the end of the day – the less you have the better. Originally I used a Freetronics TwentyTen board – which has now been superseded by their Eleven board, however they’re both identical for the purposes of this tutorial.

So what to do? As regular readers will know, my preferred board is the Freetronics Eleven, and within this we have a solution to the following problem:

The Freetronics team have thoughtfully provided a prototyping area in their board – and that will be a perfect home for the real time clock system. Being a cheapskate and a masochist – instead of following others by using a smaller RTC module I will instead use parts already in stock (except for the battery) and install my own circuit. So, as always – we need a plan. The circuit itself is quite simple, the DS1307 data sheet has a fine example on page thirteen, and here is my interpretation:

The CR1220 battery was chosen over the usual CR2032 due to the smaller diameter. According to the DS1307 data sheet, the battery should last around ten years if it has a capacity of 48 mAh. Our CR1220 is 35 mAh – which will do nicely, perhaps seven years or so. That will have to do. Don’t forget to check the voltage of the battery before installation – it should be just over three volts.

Now to get everything arranged in the prototyping area. When doing this it pays to always have the schematic in front of you as well so you can refer to it when necessary. Planning to use protoboard of any size requires a good plan as well. After spending some time considering component placement, the final layout was as follows:

Each square on the grid represents one hole on the board. After you see the images below, everything will make sense. Before soldering away, it will pay to give the prototyping area a quick clean with some PCB cleaner.

Now it is finally time to get soldering. The first items were the battery, crystal and the resistors. Although the battery was designed to be soldered, I am always a little wary when applying heat to them. Two seconds with the hot iron was enough.

When soldering in the crystal (or anything else), try to keep in mind what the leads will be connecting to. For example, the crystal legs will need to connect to pins 1 and 2 of the IC socket. So bend the crystal leads in the direction of the respective IC socket pins. Doing so will make creating solder joins between them much easier:

The resistors were simple enough. Keep the excess clippings to make jumpers with later. Also notice how the right hand leg of R3 was bent around and brought back up to the top row – this is to help make connections with the 5V rail link:

The next item was the IC socket. Nothing to worry about there, just drop it in and solder away. Don’t forget to bridge the crystal pins to socket pins one and two, and the battery positive pin to IC socket pin three.

Next for the SQW pin. The DS1307 can also output a nice square wave at either 1Hz, 4.096 kHz, 8.192 kHz or 32.768 kHz, with the resulting signal being found on pin 7. It isn’t something really used that often, but you never know. So I soldered in one of these pins, which should make it easy enough to use later on:

Note that if you are using the SQW function, the DS1307 will merrily pulse away once it is set, until the power is cut – the square-wave generator is autonomous to the I2C bus once it has been set. And it remembers (as long as the backup battery is fine). For example, you can upload a sketch to set the SQW to 4.096 kHz, remove power, yank out the ATmega328, power up – and the SQW is still active.

Next we turn the board over, and solder in our jumper wires:

The lead on the top runs from the right-hand side of the pull-up resistors R1~R3 (when facing the top of the board) to the 5V pad. The bottom lead runs from pin four of the IC socket to the GND pad. The negative pin of the battery is also bent over and soldered to the GND pad. Also, connect all the resistors together as shown in the above image (below the TX pin). The next step is turn the board back over and make some more wired connections, the first being pin eight of the IC socket to the resistors and then to the 5V link on the rear:

The next are somewhat longer, they are the leads for the I2C bus. Run a wire from next to IC socket pin six all the way to (and through) the bottom-right hole of the TwentyTen (when facing the top); this will be the SCL line and soldered to analogue 5. Repeat again from IC socket pin five, this is the SDA line (as above) for analogue 4. The joints you have to solder them onto are not that large, however it can be done. Before soldering the wires in, heat up the existing joint to melting point then let it cool again – this makes actually soldering the wire in a lot easier:

And there we have it. At this stage, don’t plug the board in. Do some quality control: check that the soldered joints are complete; check that solder has bridged where you need it, and not where you don’t; use the continuity function (‘beeper’) of a multimeter to spot-check for shorts, and also follow the new 5V and GND lines to ensure they are connected correctly. And finally, insert the DS1307 IC into the socket.

OK – now for some test timing. If you have not worked with the DS1307 IC before, there is a full explanation of how it works within our Arduino tutorials. Here’s a sketch you can use to test the real-time clock. Once you have uploaded that sketch, open the serial monitor box at 9600 bps, and you should have something like this:

Now let’s check the 1 Hz output from the SQW pin:

Recall that you can generate four frequencies with your DS1307, here is an example sketch that does just that:

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

/*

DS1307 Square-wave machine

Used to demonstrate the four different square-wave outputs from Maxim DS1307

See page nine of data sheet for more information

John Boxall - tronixstuff.com

*/

#include "Wire.h"

#define DS1307_I2C_ADDRESS 0x68 // each I2C object has a unique bus address, the DS1307 is 0x68

voidsetup()

{

Wire.begin();

}

voidsqw1()// set to 1Hz

{

Wire.beginTransmission(DS1307_I2C_ADDRESS);

Wire.write(0x07);// move pointer to SQW address

Wire.write(0x10);// sends 0x10 (hex) 00010000 (binary)

Wire.endTransmission();

}

voidsqw2()// set to 4.096 kHz

{

Wire.beginTransmission(DS1307_I2C_ADDRESS);

Wire.write(0x07);// move pointer to SQW address

Wire.write(0x11);// sends 0x11 (hex) 00010001 (binary)

Wire.endTransmission();

}

voidsqw3()// set to 8.192 kHz

{

Wire.beginTransmission(DS1307_I2C_ADDRESS);

Wire.write(0x07);// move pointer to SQW address

Wire.write(0x12);// sends 0x12 (hex) 00010010 (binary)

Wire.endTransmission();

}

voidsqw4()// set to 32.768 kHz (the crystal frequency)

{

Wire.beginTransmission(DS1307_I2C_ADDRESS);

Wire.write(0x07);// move pointer to SQW address

Wire.write(0x13);// sends 0x13 (hex) 00010011 (binary)

Wire.endTransmission();

}

voidsqwOff()

// turns the SQW off

{

Wire.beginTransmission(DS1307_I2C_ADDRESS);

Wire.write(0x07);// move pointer to SQW address

Wire.write(0x00);// turns the SQW pin off

Wire.endTransmission();

}

voidloop()

{

sqw1();

delay(5000);

sqw2();

delay(5000);

sqw3();

delay(5000);

sqw4();

delay(5000);

sqwOff();

delay(5000);

}

and here is the result – measured on a freqency counter:

My frequency counter is around twenty-two years old, please be patient with it as the sampling rate is not the best.

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

In this tutorial we make an Arduino-compatible board that holds the microcontroller in a ZIF socket.

Updated 18/03/2013

Today we are going to make a different type of Arduino-compatible board, one that has a ZIF (“zero insertion force”) socket. Our reason for making this is simple – now and again you may need to program more than one bootrom with a sketch, for example if you were planning to make your own electronics kits that were based on the Arduino system. Your alternative would be to use a chip puller and constantly insert and remove microcontrollers from your usual Arduino or compatible board – which is bad for the board, bad for the chips (the friction and pressure on the legs, as well as possible static build-up), and bad for your wrist.

So here is our problem – we need a board with a ZIF socket:

The Eleven board is great, but we just cannot squeeze in the socket. So instead, let’s make our own. Like any project, the first thing to do is plan the circuit and make a schematic:

You have to hand it to the Arduino team, they have made things very easy for us. As we are not using this board for day to day use, all we need is enough circuitry to enable programming. In this case, the connection between the board and the PC will be made with an FTDI cable (these offer an interface between serial and the USB port):

Furthermore, we will use the 5 V power supply from the USB port via the FTDI cable as well. Easy! So now it is time to collect the required parts:

You will notice in the photo above there is a button, originally I was going to have a reset button, but after testing it proved unnecessary. Our required parts consist of:

one 16 MHz ceramic resonator (easier than using a crystal and two capacitors, timing is not critical as this is only a programming board)

6-pin header strip to connect the FTDI cable to the board

an FTDI cable (the 5v one)

two 0.1uF ceramic capacitors

one 10k ohm resistor

some rubber feet (to protect your desk when using the board

some veroboard

hookup wire, some solder, and the usual tools

Before soldering away, it pays to test the circuit on a breadboard. At this stage you can test the operation, program the microcontroller, and test that microcontroller in another board:

Again, you can ignore the button. For testing purposes, I uploaded the “blink” sketch to the microcontroller, then tested that unit in the Eleven. The LED blinked as expected, so all was good. I repeated the process a few times, but uploaded a different sketch every second time, and re-inserted the bootrom between every upload. After ten cycles of doing this, I was confident with the design, so transferred the lot to the permanent veroboard:

The black marks on the board are to help me navigate, for example the arrow means the 5 V rail, etc. Now for the rear end:

There are high-resolution photos in flickr if you want to follow this design exactly.

Before using the veroboard, experience has taught me that they are always dirty and solder doesn’t take too well. If possible, try and clean your veroboard first with some cleaning spray, usually an aerosol package available from most electronics retailers. Or even just a damp cloth, then dry the board afterwards with a dry cloth. Moving on…

Before testing the completed board, please double check the routing and that you have cut the correct PCB tracks. If you are unsure about some solder joints, use the continuity function or resistance function of a multimeter to check for shorts between tracks.

After the board passed those tests, I stuck on the feet – and admired the finished product:

However, it was time to repeat the testing. If I may make a general observation, try and test things as you move along, step by step. For example, with this project, don’t skip the breadboarding step. It is important to check the design works. Don’t skip checking for solder bridges, or not double-check your routing. It is always much easier to fix a mistake when it has been made, then to have to troubleshoot a ‘completed’ project.

But at the end of the day, I now have something that is useful and will save me time during kit production (still in design stage people), making a few blinky offspring, and prevent damaging my regular boards. High resolution images are available from flickr.

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