Kit review – Protostack ATmega32 Development Kit
Introduction
For those of you prototyping with larger Atmel AVR microcontrollers such as the ATmega32, it can be inconvenient to continually assemble a circuit onto a solderless breadboard that includes power, programming header and a few basics – or you might want to create a one-off product without waiting for a PCB to be made. If these are issues for you, or you’re interested in working with AVRs then the subject of this review may be of interest – the ATmega32 Development Kit from Protostack. The kit is one of a range that spans from the ATmega8, and gives you almost everything needed to work with the microcontroller. We’ve assembled and experimented with the ATmega32 kit, so read on to find out more.
Assembly
The kit arrives in a typical anti-static package with the contents and URL on the front:
The PCB is large, measuring 127 x 94 mm, made from heavy 1.6 mm FR4 PCB and all the holes are through-plated. And as you can see from the images below, there’s plenty of prototyping space and power/GND rails:
The included parts allow you to add a power supply, polyfuse, smoothing capacitors for the power, programmer socket, external 16 MHz crystal, a DC socket, IC socket, a lonely LED and of course the ATmega32A (which is a lower-power version of the ATmega32):
You can download the user guide from the product page, which details the board layout, schematic and so on. When soldering the parts in, just start with the smallest-profile parts first and work your way up. There’s a few clever design points, such as power regulator – there’s four holes so you can use both “in-GND-output” and “GND-output-input” types:
… and the layout of the prototyping areas resemble that of a solderless breadboard, and the power/GND rails snake all around – so transferring projects won’t be difficult at all:
If you need to connect the AVcc to Vcc, the components and board space are included for a low-pass filter:
And if you get carried away and need to use two or more boards at once – they’re stackable:
Moving forward
After assembling the board and inserting the ATmega32, you can use an AVR programmer to check it’s all working (and of course program it). With a 10-pin interface USBASP inserted, I headed over to the AVRdude folder on my PC and entered:
avrdude -c usbasp -p m32
which (as all was well) resulted with:
Awesome – it’s nice to have something that just works. Let the experimenting begin!
Competition
Would you like the chance to win a kit? It’s easy. Clearly print your email address on a postcard, and mail it to:
Protostack Competition, PO Box 5435, Clayton 3168, Australia
Entries must be received by the 4th of August 2013. One postcard will then be drawn at random, and the winner will receive one ATmega32 kit delivered by Australia Post standard air mail. You can enter as many times as you like. We’re not responsible for customs or import duties, VAT, GST, postage delays, non-delivery or whatever walls your country puts up against receiving inbound mail.
Conclusion
It’s a solid kit, the PCB is solid as a rock, and it worked. However it could really have used some spacers or small rubber feet to keep the board off the bench. Otherwise the kit is excellent, and offers a great prototyping area to work with your projects. If you order some, Protostack have a maximum delivery charge of $9 so you won’t get burned on delivery to far-flung places. Larger photos available on flickr. And if you made it this far – check out my new book “Arduino Workshop” from No Starch Press.
Please note that the ATMEGA32A Development Kit in this review is a promotional consideration from Protostack.
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.
Project: Clock Four – Scrolling text clock
Introduction
Time for another instalment in my highly-irregular series of irregular clock projects. In this we have “Clock Four” – a scrolling text clock. After examining some Freetronics Dot Matrix Displays in the stock, it occurred to me that it would be neat to display the time as it was spoken (or close to it) – and thus this the clock was born. It is a quick project – we give you enough to get going with the hardware and sketch, and then you can take it further to suit your needs.
Hardware
You’ll need three major items – An Arduino Uno-compatible board, a real-time clock circuit or module using either a DS1307 or DS3232 IC, and a Freetronics DMD. You might want an external power supply, but we’ll get to that later on.
The first stage is to fit your real-time clock. If you are unfamiliar with the operation of real-time clock circuits, check out the last section of this tutorial. You can build a RTC circuit onto a protoshield or if you have a Freetronics Eleven, it can all fit in the prototyping space as such:
If you have an RTC module, it will also fit in the same space, then you simply run some wires to the 5V, GND, A4 (for SDA) and A5 (for SCL):
By now I hope you’re thinking “how do you set the time?”. There’s two answers to that question. If you’re using the DS3232 just set it in the sketch (see below) as the accuracy is very good, you only need to upload the sketch with the new time twice a year to cover daylight savings (unless you live in Queensland). Otherwise add a simple user-interface – a couple of buttons could do it, just as we did with Clock Two. Finally you just need to put the hardware on the back of the DMD. There’s plenty of scope to meet your own needs, a simple solution might be to align the control board so you can access the USB socket with ease – and then stick it down with some Sugru:
With regards to powering the clock – you can run ONE DMD from the Arduino, and it runs at a good brightness for indoor use. If you want the DMD to run at full, retina-burning brightness you need to use a separate 5 V 4 A power supply. If you’re using two DMDs – that goes to 8 A, and so on. Simply connect the external power to one DMD’s terminals (connect the second or more DMDs to these terminals):

The Arduino Sketch
You can download the sketch from here. It was written only for Arduino v1.0.1. The sketch has the usual functions to set and retrieve the time from DS1307/3232 real-time clock ICs, and as usual with all our clocks you can enter the time information into the variables in void setup(), then uncomment setDateDs1307(), upload the sketch, re-comment setDateDs1307, then upload the sketch once more. Repeat that process to re-set the time if you didn’t add any hardware-based user interface.
Once the time is retrieved in void loop(), it is passed to the function createTextTime(). This function creates the text string to display by starting with “It’s “, and then determines which words to follow depending on the current time. Finally the function drawText() converts the string holding the text to display into a character variable which can be passed to the DMD.
And here it is in action:
Conclusion
This was a quick project, however I hope you found it either entertaining or useful – and another random type of clock that’s easy to reproduce or modify yourself. We’re already working on another one which is completely different, so stay tuned.
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.
Review: Gooligum Electronics PIC Training Course and Development Board
Introduction
[Updated 18/06/2013]
There are many types of microcontrollers on the market, and it would be fair to say one of the two most popular types is the Microchip PIC series. The PICs are great as there is a huge range of microcontrollers available across a broad range of prices. However learning how to get started with the PIC platform isn’t exactly simple. Not that we expect it to be, however a soft start is always better. There are some older books, however they can cost more than $100 – and are generally outdated. So where do you start?
It is with this problem in mind that led fellow Australian David Meiklejohn to develop and offer his PIC Training Course and Development Board to the marketplace via his company Gooligum Electronics.
In his words:
There is plenty of material available on PICs, which can make it daunting to get started. And some of the available material is dated, originally developed before modern “flash” PICs were available, or based on older devices that are no longer the best choice for new designs. Our approach is to introduce PIC programming and design in easy stages, based on a solid grounding in theory, creating a set of building blocks and techniques and giving you the confidence to draw on as we move up to more complex designs.
So in this article we’ll examine David’s course package. First of all, let’s look at the development board and inclusions. Almost everything you will need to complete all the lessons is included in the package, including the following PIC microcontrollers:
You can choose to purchase the board in kit form or pre-assembled. If you enjoy soldering, save the money and get the kit – it’s simple to assemble and a nice way to spend a few hours with a soldering iron.
Although the board includes all the electronic components and PICs – you will need are a computer capable of running Microchip MPLAB software, a Microchip PICkit3 (or -2) programming device and an IC extractor. If you’re building the kit, a typical soldering iron and so on will be required. Being the ultra-paranoid type, I bought a couple extra of each PIC to have as spares, however none were damaged in my experimenting. Just use common-sense when handling the PICs and you will be fine.
Assembly
Putting the kit board together wasn’t difficult at all. There isn’t any surface-mount parts to worry about, and the PCB is silk-screened very well:
The rest of the parts are shipped in antistatic bags, appropriately labelled and protected:
Assembly was straight forward, just start with the low-profile parts and work your way up. The assembly guide is useful to help with component placement. After working at a normal pace, it was ready in just over an hour:
The Hardware
Once assembled (or you’ve opened the packaging) the various sections of the board are obvious and clearly labelled – as they should be for an educational board. You will notice a large amount of jumper headers – they are required to bridge in and out various LEDs, select various input methods and so on. A large amount of jumper shunts is included with the board.
It might appear a little disconcerting at first, but all is revealed and explained as you progress through the lessons. The board has decent rubber feet, and is powered either by the PICkit3 programmer, or a regulated DC power source between 5 and 6V DC, such as from a plug-pack if you want to operate your board away from a PC.
However there is a wide range of functions, input and output devices on the board – and an adjustable oscillator, as shown in the following diagram:
The Lessons
There is some assumed knowledge, which is a reasonable understanding of basic electronics, some computer and mathematical savvy and the C programming language.
You can view the first group of lessons for free on the kit website, and these are included along with the additional lessons in the included CDROM. They’re in .pdf format and easy to read. The CDROM also includes all the code so you don’t have to transcribe it from the lessons. Students start with an absolute introduction to the system, and first learn how to program in assembly language in the first group of tutorials, followed by C in the second set.
This is great as you learn about the microcontroller itself, and basically start from the bottom. Although it’s no secret I enjoy using the Arduino system – it really does hide a lot of the actual hardware knowledge away from the end user which won’t be learned. With David’s system – you will learn.
If you scroll down to the bottom of this page, you can review the tutorial summaries. Finally here’s a quick demonstration of the 7-segment displays in action:
Update – 18/06/2013
David has continued publishing more tutorials for his customers every few months – including such topics as the EEPROM and pulse-width modulation. As part of the expanded lessons you can also get a pack which allows experimenting with electric motors that includes a small DC motor, the TI SN75441 h-bridge IC, N-channel and P-channel MOSFETS and more:
So after the initial purchase, you won’t be left on your own. Kudos to David for continuing to support and develop more material for his customers.
Where to from here?
Once you run through all the tutorials, and feel confident with your knowledge, the world of Microchip PIC will be open to you. Plus you now have a great development board for prototyping with 6 to 14-pin PIC microcontrollers. Don’t forget all the pins are brought out to the row of sockets next to the solderless breadboard, so general prototyping is a breeze.
Conclusion
For those who have mastered basic electronics, and have some C or C-like programming experience from using other development environments or PCs – this package is perfect for getting started with the Microchip PIC environment. Plus you’ll learn about assembly language – which is a good thing. I genuinely recommend this to anyone who wants to learn about PIC and/or move into more advanced microcontroller work. And as the entire package is cheaper than some books – you can’t go wrong. The training course is available directly from the Gooligum website.
Disclaimer - The Baseline and Mid-Range PIC Training Course and Development Board was a promotional consideration from Gooligum Electronics.
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.
Project: Clock Three – A pillow clock
A pillow clock? How? Read on…
Updated 18/03/2013
Time for another instalment in my irregular series of irregular clock projects. In contrast with the minimalism of Clock Two, in this article we describe how to build a different type of clock – using the “lilypad” style of Arduino-compatible board and components designed for use in e-textiles and wearable electronics. As the LilyPad system is new territory for us, the results have been somewhat agricultural. But first we will examine how LilyPad can be implemented, and then move on to the clock itself.
The LilyPad system
By now you should have a grasp of what the whole Arduino system is all about. If not, don’t panic – see my series of tutorials available here. The LilyPad Arduino boards are small versions that are designed to be used with sewable electronics – in order to add circuitry to clothing, haberdashery items, plush toys, backpacks, etc. There are a few versions out there but for the purpose of our exercise we use the Protosnap Lilypad parts which come in one PCB unit for practice, and then can be ‘snapped out’ for individual use. Here is an example in the following video:
The main circular board in the Arduino-type board which contains an ATmega328 microcontroller, some I/O pins, a header for an FTDI-USB converter and a Li-Ion battery charger/connector. As an aside, this package is good start – as well as the main board you receive the FTDI USB converter, five white LEDs, a buzzer, vibration module, RGB LED, a switch, temperature sensor and light sensor. If you don’t want to invest fully in the LilyPad system until you are confident, there is a smaller E-Sewing kit available with some LEDs, a battery, switch, needle and thread to get started with.
Moving forward – how will the parts be connected? Using thread – conductive thread. For example:
This looks and feels like normal thread, and is used as such. However it is conductive – so it doubles as wire. However the main caveat is the resistance – conductive thread has a much higher resistance than normal hook-up wire. For example, measuring a length of around eleven centimetres has a resistance of around 11Ω:
So don’t go too long with your wire runs otherwise Ohm’s Law will come into play and reduce the available voltage. It is wise to try and minimise the distance between parts otherwise the voltage potential drop may be too much or your digital signals may have issues. Before moving on to the main project it doesn’t hurt to practice sewing a few items together to get the hang of things. For example, run a single LED from a digital output – here I was testing an LED by holding it under the threads:
Be careful with loose live threads – it’s easy to short out a circuit when they unexpectedly touch. Finally for more information about sewing LilyPad circuits, you can watch some talent from Sparkfun in this short lesson video:
And now to the Clock!
It will be assumed that the reader has a working knowledge of Arduino programming and using the DS1307 real-time clock IC. The clock will display the time using four LEDs – one for each digit of the time. Each LED will blink out a value which would normally be represented by the digit of a digital clock (similar to blinky the clock). For example, to display 1456h the following will happen:
- LED 1 blinks once
- LED 2 blinks four times
- LED 3 blinks five times
- LED 4 blinks six times
If a value of zero is required (for example midnight, or 1000h) the relevant LED will be solidly on for a short duration. The time will be set when uploading the sketch to the LilyPad, as having two or more buttons adds complexity and increases the margin for error. The only other hardware required will be the DS1307 real-time clock IC. Thankfully there is a handy little breakout board available which works nicely. Due to the sensitivity of the I2C bus, the lines from SDA and SCL to the LilyPad will be soldered. Finally for power, we’re using a lithium-ion battery that plugs into the LilyPad. You could also use a separate 3~3.3 V DC power supply and feed this into the power pins of the FTDI header on the LilyPad.
Now to start the hardware assembly. First – the RTC board to the LilyPad. The wiring is as follows:
- LilyPad + to RTC 5V
- LilyPad – to RTC GND
- LilyPad A4 to RTC SDA
- LilyPad A5 to RTC SCL
At this stage it is a good idea to test the real-time clock. Using this sketch, you can display the time data on the serial monitor as such:
Sewing it together…
Once you have the RTC running the next step is to do some actual sewing. Real men know how to sew, so if you don’t – now is the time to learn. For our example I bought a small cushion cover from Ikea. It is quite dark and strong – which reduces the contrast between the conductive thread and the material, for example:
However some people like to see the wires – so the choice of slip is up to you. Next, plan where you want to place the components. The following will be my rough layout, however the LilyPad and the battery will be sewn inside the cover:
The LilyPad LEDs have the current-limiting resistor on the board, so you can connect them directly to digital outputs. And the anode side is noted by the ‘+’:
For our example we connect one LED each to digital pins six, nine, ten and eleven. These are also PWM pins so a variety of lighting effects are available. The cathode/negative side of the LED modules are connected together and then return to the ‘-’ pad on the LilyPad. The actual process of sewing can be quite fiddly – so take your time and check your work. Always make note to not allow wires (threads) to touch unless necessary. It can help to hold the LilyPad up and let the cloth fall around it to determine the location of the LilyPad on the other side, for example:
As this was a first attempt – a few different methods of sewing the parts to the cloth were demonstrated. This becomes evident when looking on the inside of the slip:
… however the end product looked fair enough:
After sewing in each LED, you could always upload the ‘blink’ sketch and adapt it to the LEDs – a simple way to test your sewing/wiring before moving forward.
The sketch…
As usual with my clock projects the sketch is based around the boilerplate “get time from DS1307″ functions. There is also the function blinkLED which is used to control the LEDs, and the time-to-blinking conversion is done in the function displayTime. For those interested, download and examine the sketch.
The results!
Finally in the video clip below our pillow clock is telling the time – currently 1144h:
So there you have it, the third of many clocks we plan to describe in the future. Once again, this project is just a demonstration – so feel free to modify the sketch or come up with your own ideas.
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.
Arduino meets Las Vegas with the Freetronics DMD
Updated 30/01/2013
Time once more to have some fun, and this time by examining the new Freetronics DMD “Dot Matrix Display”. We will look at the setup and operation of the display. In a nutshell the DMD comprises of a board measuring approximately 320mm across by 160mm which contains 16 rows of 32 high-intensity red LEDs. For example, in the off state:
Connection of the DMD to your Arduino-compatible board is quite simple. Included with each DMD is a 2×8 IDC cable of around 220mm in length, and a PCB to allow direct connection to the Arduino digital pins D6~13:
Finally the cable connects to the left-hand socket on the rear of the DMD:
You can also daisy-chain more than one display, so a matching output socket is also provided. Finally, an external power supply is recommended in order to drive the LEDs as maximum brightness – 5V at ~4 A per DMD. This is connected to a separate terminal on the rear of the board:
Do not connect these terminals to the 5V/GND of your Arduino board!
A power cable with lugs is also included so you can daisy chain the high-intensity power feeds as well. When using this method, ensure your power supply can deliver 5V at 4A for each DMD used – so for two DMDs, you will need 8A, etc. For testing (and our demonstration) purposes you can simply connect the DMD to your Arduino via the IDC cable, however the LEDs will not light at their full potential.
Using the display with your Arduino sketches is quite simple. There is an enthusiastic group of people working on the library which you will need, and you can download it from and follow the progress at the DMD Github page and forks. Furthermore, there is always the Freetronics forum for help, advice and conversation. Finally you will also need the TimerOne library – available from here.
However for now let’s run through the use of the DMD and get things moving. Starting with scrolling text – download the demonstration sketch from here. All the code in the sketch outside of void loop() is necessary. Replace the text within the quotes with what you would like to scroll across the display, and enter the number of characters (including spaces) in the next parameter. Finally, if you have more than one display change the 1 to your number of displays in #define DISPLAYS_ACROSS 1.
Here is a quick video of our example sketch:
Now for some more static display functions – starting with clearing the display. You can use
dmd.clearScreen( true );
to turn off all the pixels, or
dmd.clearScreen( false );
to turn on all the pixels.
Note: turning on more pixels at once increases the current draw. Always keep this in mind and measure with an ammeter if unsure.
dmd.selectFont(SystemFont5x7);
for a smaller font or
dmd.selectFont(Arial_Black_16);
for a larger font. To position a single character on the DMD, use:
dmd.drawChar( x, y, 'x', GRAPHICS_NORMAL );
which will display the character ‘x’ at location x,y (in pixels – starting from zero). For example, using
dmd.drawChar( 10, 5, 'A', GRAPHICS_NORMAL );
results with:
Note if you have the pixels on ‘behind’ the character, the unused pixels in the character are not ‘transparent’. For example:
However if you change the last parameter to GRAPHICS_NOR, the unused pixels will become ‘transparent’. For example:
You can also use the parameter GRAPHICS_OR to overlay a character on the display. This is done with the blinking colon in the example sketch provided with the library.
Next, to draw a string (group of characters). This is simple, just select your font type and then use (for example):
dmd.drawString( 0,0, "Hello,", 5, GRAPHICS_NORMAL ); dmd.drawString( 2,9, "world,", 5, GRAPHICS_NORMAL );
Again, the 5 is a parameter for the length of the string to display. This results in the following:
Next up we look at the graphic commands. To control an individual pixel, use
dmd.writePixel( x,y, GRAPHICS_NORMAL,1); // turn on a pixel at location x,y
And changing the 1 to a 0 turns off the pixel. To draw a circle with the centre at x,y and a radius r, use
dmd.drawCircle( x, y, r, GRAPHICS_NORMAL );
To draw a line from x1, y2 to x2, y2, use:
dmd.drawLine( x1, y1, x2, y2, GRAPHICS_NORMAL );
To draw a rectangle from x1, y2 to x2, y, use:
dmd.drawBox(x1, y1, x2, y2, GRAPHICS_NORMAL );
And to draw a filled rectangle use:
dmd.drawFilledBox(x1, y1, x2, y2, GRAPHICS_NORMAL );
Now let’s put those functions to work. You can download the demonstration sketch from here, and watch the following results:
Update – the DMD will also be available in other colours, such as white:
So there you have it, an inexpensive and easy to use display board with all sorts of applications. Although the demonstrations contained within this article were rather simple, you now have the knowledge to apply your imagination to the DMD and display what you like. For more information, support and conversation visit the Freetronics product page and support forum.
Disclaimer – The parts reviewed in this article are a promotional consideration made available by Freetronics.
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.
Review – Freetronics Module Family
Hello
In this article we examine a new range of eleven electronic modules from Freetronics. When experimenting with electronics or working on a prototype of a design, the use of electronic components in module form can make construction easier, and also reduce the time between thoughts and actually making something
So let’s have a look at each module in more detail…
This is a tiny switchmode voltage regulator with two uses – the first being regulation of higher voltage up to 28V carried via an Ethernet cable to a Freetronics Ethernet shield or EtherTen to power the board itself. The PCB is designed to drop into the shield or EtherTen as such:
… and converts the incoming voltage down to 7V which can be regulated by the EtherTen’s inbuilt regulator. The second use of this board is a very handy power supply for breadboarding or other experimentation. By bridging the solder pads on the rear of the board, the output is set to 5V DC, as such:
Note the addition of the header pins, which make insertion into a breadboard very easy – so now you have a 5V 1A DC power supply. For more information visit the product page.
This module contains an On Semi NTD5867NL MOSFET which allows the switching of a high current and voltage line – 60V at up to 20A – with a simple Arduino or other MCU digital output pin. The package is small and also contains enlarged holes for direct connection of high-current capability wire:
The onboard circuitry includes a pull-down resistor to ensure the MOSFET is off by default. For more information see the product page.
This is a very simple and inexpensive method to interface 3.3V sensors to 5V microcontrollers in either direction.The module contains four independent channels, as shown in the image below:
However you can interface any low or higher voltage, as long as you connect the low and high voltages to the correct sides (marked on the PCB’s silk screen). For more information please visit the product page.
Surprisingly this module contains a RGB LED module (red, green and blue LEDs) which is controlled by a WS2801 constant-current LED driver IC. This module is only uses two digital output pins, and can be daisy-chained to control many modules with the same two pins. The connections are shown clearly on the module:
The WS2801 controller IC is on the rear:
There are several ways to control the LEDs. One way is using the sketch from the product home page, which results with the following demonstration output:
Or there is a unique Arduino WS2801 library available for download from here. Using the strandtest example included with the library results with the following:
During operation the module used less than 24 mA of current and therefore can happily run from a standard Arduino-type board without any issues. For more information please visit the product page.
TEMP Temperature Sensor Module
This module allows the simple measurement of temperature using the popular DS18B20 temperature sensor. You can measure temperatures between -55° and 125°C with an accuracy of +/- 0.5°C. Furthermore as the sensor uses the 1-wire bus, you can daisy-chain more than one sensor for multiple readings in the one application. The board is simple to use, and also contains a power-on LED:
Using the demonstation Arduino sketch from the product page results in the following output via the serial monitor:
Using this module is preferable to the popular Analog Devices TMP36, as it has an analogue output which can be interfered with, and requires an analogue input pin for each sensor, whereas this module has a digital output and as mentioned previously can be daisy-chained. For more information please visit the product page.
Humidity and Temperature Sensor Module
For the weather-measuring folk here is a module with temperatures and humidity. Using the popular DHT22 sensor module the temperature range is -4°C to +125°C with an accuracy of +/- 0.5°C, and humidity with an accuracy of between two and five percent. Only one digital input pin is required, and the board is clearly labelled:
There is also a blue power-on LED towards the top-right of the sensor. Using the module is quite simple with Arduino – download and use the example sketch included in the sensor library you can download from here. For the demonstration connect the centre data pin to Arduino digital two. Here is an example of the demonstration output:
Although the update speed is not lightning-fast, this should not be an issue unless you’re measuring real-time external temperature of your jet or rocket. For more information please see the product page.
Shift Register/Expansion Module
This board uses a 74HC595 serial-in parallel-out shift register which enables you to control eight digital outputs with only three digital pins, for example:
You can daisy-chain these modules to increase the number of digital outputs in multiples of eight, all while only using the three digital output pins on your Arduino or other microcontroller. For more information about how to use shift registers with Arduino systems, read our detailed tutorial. Otherwise for more information about the module please visit the product page.
Hall Effect Magnetic and Proximity Sensor Module
This module contains a sensor which changes output from HIGH to LOW when a magnetic presence is detected, for example a magnet. The board also has an LED which indicates the presence of the magnet to aid in troubleshooting:
Using this module and a small magnet would be an easy way to create a speedometer for a bicycle, the module is mounted to the fork, and the magnet on the rim of the front wheel. For more ideas consider the speedometer project in this tutorial. Otherwise for more information about this module please visit the product page.
This module performs two functions – it can return the sound pressure level (SPL) or the amplified audio waveform from the electret microphone. The LED (labelled “DETECT”) on the board visually displays an approximation of the SPL – for example:
… however the value can be returned by using an analogue input pin on an Arduino (etc). to return a numerical value. To do this connect the SPL pin to the analogue input. The MIC pin is used to take the amplified output from the microphone, to be processed by an ADC or used in an audio project. For more information please visit the product page.
This module uses the TEMT6000 light sensor which returns more consistent values than can be possible using a light-dependent resistor. It outputs a voltage from the OUT pin that is proportional to the light level. The module is very small:
Use is simple – just measure the value returned from the OUT pin using an analogue input pin on your Arduino (etc). For more information please visit the product page. And finally, the:
This module contains a piezoelectric element that can be used to generate sounds (in the form of musical buzzes…):
Driving the buzzer is simple, just use pulse-width modulation. Arduino users can find a good demonstration of this here. Furthermore, as piezoelectric elements can also generate a small electrical current when vibrated, they can be used as “shock” detectors by measuring the voltage across the terminals of the element. The procedure to do this is also explained clearly here.
Now for a final demonstration – we use the light sensor to demonstrate making some noise with the buzzer module:
One final note I would like to make is that the design and construction quality of each module is first rate. The PCBs are strong, and the silk-screening is useful and descriptive. If you find the need for some or all of the functions made available in this range, you could do worse by not considering a Freetronics unit. Finally, although this has only been a short introduction to the modules for now, we will make use of them in later projects.
The modules are available directly from Freetronics or through their network of resellers.
Disclaimer – Modules reviewed in this article are a promotional consideration made available by Freetronics
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.
Tutorial – Parallax Ping))) Ultrasonic Sensor
Sense distance with ultrasonic sensors in chapter forty-five 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 05/02/2013
Whilst being a passenger in a vehicle with a ‘reversing sensors’, I became somewhat curious as to how the sensors operated and how we can make use of them. So for this chapter we will investigate an ultrasonic sensor from Parallax called the Ping)))™ Ultrasonic Distance Sensor. It can measure distances between ~2cm and ~3m in length. Here is our example sensor:
(Memories of Number Five …)
Parallax have done a lot of work, the board contains not just the bare sensor hardware but controller circuitry as well:
Which is great as it leaves us with only three pins – 5V, GND and signal. More on those in a moment, but first…
How does it work?
Good question. The unit sends out an ultrasonic (a sound that has a frequency which is higher than can be heard by the human ear) burst of sound from one transducer (the round silver things) and waits for it bounce off an object and return – which is detected by the other transducer. The board will then return to us the period of time taken for this process to take, which we can interpret to determine the distance between the sensor and the object from which the ultrasonic sound bounced from.
The Ping))) only measures a distance when requested – to do this we send a very short HIGH pulse of five microseconds to the signal pin. After a brief moment a pulse will come from the board on the same signal pin. The period of this second pulse is the amount of time the sound took to travel out and back from the sensor – so we divide it by two to calculate the distance. Finally, as the the speed of sound is 340 metres per second, the Arduino sketch can calculate the distance to whatever units required.
It may sound complex, but it is not – so let’s run through the theory of operation with an example. Using our digital storage oscillscope we have measured the waveforms on the signal pin during a typical measurement. Consider the following example of measuring a distance of 12cm (click image to enlarge):
You can see the 5uS pulse in the centre and the pulse returned from the sensor board on the right. Now to zoom in on the returned pulse (click image to enlarge):
Without being too picky the pulse is roughly 720uS (microseconds) long – the duration of ultrasonic sound’s return trip from the sensor board. So we divide this by two to find the time to travel the distance – 360uS. Recall the speed of sound is 340 metres per second – which converts to 29.412 uS per centimetre. So, 360uS divided by 29.412 uS gives 12.239902081… centimetres. Rounded that gives us 12 centimetres. Easy!
Finally, there are some limitations to using the Ping))) sensor. Download the data sheet (pdf) and read pages three to five for information on how to effectively mount the sensor and the sensitivity results from factory resting.
How do we use it with Arduino?
As described previously we first need to send a 5uS pulse, then listen for the return pulse. The following sketch does just that, then converts the data to centimetres and displays the result on the serial monitor. The code has been commented to explain each step.
// Example 45.1 - tronixstuff.wordpress.com - CC by-sa-nc // Connect Ping))) signal pin to Arduino digital 8
int signal=8; int distance; unsigned long pulseduration=0;
void setup()
{
pinMode(signal, OUTPUT);
Serial.begin(9600);
}
void measureDistance()
{
// set pin as output so we can send a pulse
pinMode(signal, OUTPUT);
// set output to LOW digitalWrite(signal, LOW); delayMicroseconds(5); // now send the 5uS pulse out to activate Ping))) digitalWrite(signal, HIGH); delayMicroseconds(5); digitalWrite(signal, LOW); // now we need to change the digital pin // to input to read the incoming pulse pinMode(signal, INPUT); // finally, measure the length of the incoming pulse pulseduration=pulseIn(signal, HIGH); }
void loop()
{
// get the raw measurement data from Ping)))
measureDistance();
// divide the pulse length by half
pulseduration=pulseduration/2;
// now convert to centimetres. We're metric here people...
distance = int(pulseduration/29);
// Display on serial monitor
Serial.print("Distance - ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
And the results of some hand-waving in the serial monitor:
So there you have it – you can now measure distance with a degree of accuracy. However that image above isn’t very exciting – instead let’s use a 7-segment display shield to get things up in lights. The shield uses the NXP SAA1064 LED display driver IC (explained quite well here). You can download the demonstration sketch from here. And now for the video:
So there you have it – now the use of the sensor is up to your imagination. Stay tuned using the methods below to see what we get up to with this sensor in the future.
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.
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/02/2013
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:
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:
- pinMode()
- digitalWrite()
- digitalRead()
- analogRead()
- analogWrite()
- shiftOut()
- pulseIn()
- millis()
- micros()
- delay()
- delayMicroseconds()
- SoftwareSerial
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
There are two ways you can program your ATtiny. Method one describes using an Arduino board, method two describes using a separate USB programmer.
Programmer method one
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 (click image to enlarge):
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 (click image to enlarge):
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. Now – scroll down until you reach the “Creating Arduino sketches for ATtinys” section to continue with the tutorial.
Programmer method two
Get yourself one of these USB programming boards:
They’re great – you just drop in the ATtiny – plus you can use it as a breakout board. And there’s an LED on pin 5 for testing with blink and debugging in general.
Insert your ATtiny into the board, plug it into a free USB port and the hardware is done. If you’re using Windows – install the necessary drivers (32-bit or 64-bit). Next, restart the Arduino IDE and select “USBtinyISP” – 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. Note that you don’t need to select a USB port in the IDE, and the option may well be blanked out – instead, check the bottom-right of the IDE. It will show the USB port being used by the programmer board, for example:
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:
void setup()
{
pinMode(0, OUTPUT);
}
void loop() {
digitalWrite(0, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(0, LOW); // set the LED off
delay(1000); // wait for a second
}
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:
void setup()
{
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
}
void loop()
{
for (int a=0; a<6; a++)
{
digitalWrite(0, HIGH); // set the LED on
digitalWrite(1, LOW); // set the LED off
delay(1000); // wait for a second
digitalWrite(0, LOW); // set the LED off
digitalWrite(1, HIGH); // set the LED on
delay(1000); // wait for a second
}
for (int z=0; z<3; z++)
{
for (int a=0; a<256; a++)
{
analogWrite(0, a);
analogWrite(1, a);
delay(1);
}
for (int a=255; a>=0; --a)
{
analogWrite(0, a);
analogWrite(1, a);
delay(1);
}
}
}
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.
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.
Tutorial: Arduino and Numeric Keypads – Part Two
Use larger numeric keypads in this addendum to chapter forty-two 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. Any files from tutorials will be found here.
Welcome back fellow arduidans!
This is the second part of our numeric keypad tutorial – in which we use the larger keypads with four rows of four buttons. For example:
Again, the keypad looks like a refugee from the 1980s – however it serves a purpose. Notice that there are eight connections at the bottom instead of seven – the extra connection is for the extra column of buttons – A~D. This example again came from Futurlec. For this tutorial you will need the data sheet for the pinouts, so download it from here (.pdf).
To use this keypad is very easy, if you haven’t already done so, download the numeric keypad Arduino library from here, copy the “Keypad” folder into your ../arduino-002x/libraries folder, then restart the Arduino IDE.
Now for our first example – just to check all is well. From a hardware perspective you will need:
- An Arduino Uno or 100% compatible board
- A 4×4 numeric keypad
- An LCD of some sort. We will be using an I2C-interface model. If you are unsure about LCD usage, please see this tutorial
- If you don’t have an LCD – that’s ok. Our demonstration sketch also sends the key presses to the serial monitor. Just delete the lines referring to Wire, LCD etc.
- Keypad row 1 (pin eight) to Arduino digital 5
- Keypad row 2 (pin 1) to Arduino digital 4
- Keypad row 3 (pin 2) to Arduino digital 3
- Keypad row 4 (pin 4) to Arduino digital 2
- Keypad column 1 (pin 3) to Arduino digital 9
- Keypad column 2 (pin 5) to Arduino digital 8
- Keypad column 3 (pin 6) to Arduino digital 7
- Keypad column 4 (pin 7) to Arduino digital 6
- the extra column in the array char keys[]
- the extra pin in the array colPins[]
- and the byte COLS = 4.
/* Example 42.3 - Numeric keypad and I2C LCD
http://tronixstuff.wordpress.com/tutorials > chapter 42a
Uses Keypad library for Arduino
http://www.arduino.cc/playground/Code/Keypad
by Mark Stanley, Alexander Brevig */
#include "Keypad.h"
#include "Wire.h" // for I2C LCD
#include "LiquidCrystal_I2C.h" // for I2C bus LCD module http://bit.ly/eNf7jM
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}};
byte rowPins[ROWS] = {
5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
9, 8, 7, 6}; //connect to the column pinouts of the keypad
int count=0;
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup()
{
Serial.begin(9600);
lcd.init(); // initialize the lcd
lcd.backlight(); // turn on LCD backlight
}
void loop()
{
char key = keypad.getKey();
if (key != NO_KEY)
{
lcd.print(key);
Serial.print(key);
count++;
if (count==17)
{
lcd.clear();
count=0;
}
}
}
And our action video:
Now for another example – we will repeat the keypad switch from chapter 42 – but allow the letters into the PIN, and use the LCD instead of LEDs for the status. In the following example, the PIN is 12AD56. Please remember that the functions correctPIN() and incorrectPIN() are example functions for resulting PIN entry – you would replace these with your own requirements, such as turning something on or off. You can download the sketch from here.
// Example 42.4 - Six-character keypad switch
// http://tronixstuff.wordpress.com/tutorials > chapter 42a
#include "Keypad.h"
#include "Wire.h" // for I2C LCD
#include "LiquidCrystal_I2C.h" // for I2C bus LCD module http://bit.ly/eNf7jM
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}};
byte rowPins[ROWS] = {
5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
9, 8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
char PIN[6]={'1','2','A','D','5','6'}; // our secret (!) number
char attempt[6]={
0,0,0,0,0,0}; // used for comparison
int z=0;
void setup()
{
lcd.init(); // initialize the lcd
lcd.backlight(); // turn on LCD backlight
lcd.print(" Enter PIN...");
}
void correctPIN() // do this if correct PIN entered
{
lcd.print("* Correct PIN *");
delay(1000);
lcd.clear();
lcd.print(" Enter PIN...");
}
void incorrectPIN() // do this if incorrect PIN entered
{
lcd.print(" * Try again *");
delay(1000);
lcd.clear();
lcd.print(" Enter PIN...");
}
void checkPIN()
{
int correct=0;
for (int q=0; q<6; q++)
{
if (attempt[q]==PIN[q])
{
correct++;
}
}
if (correct==6)
{
correctPIN();
} else
{
incorrectPIN();
}
for (int zz=0; zz<6; zz++) // wipe attempt
{
attempt[zz]=0;
}
}
void readKeypad()
{
char key = keypad.getKey();
if (key != NO_KEY)
{
switch(key)
{
case '*':
z=0;
break;
case '#':
delay(100); // for extra debounce
lcd.clear();
checkPIN();
break;
default:
attempt[z]=key;
z++;
}
}
}
void loop()
{
readKeypad();
}
Now let’s see it in action:
So now you have the ability to use twelve and sixteen-button keypads with your Arduino systems.
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.
Tutorial: Arduino Port Manipulation
This is chapter forty-three 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. Any files from tutorials will be found here.
[Updated 19/01/13]
In this article we are going to revisit the I/O pins, and use what is called “Port Manipulation” to control them in a much faster manner than using digitalWrite()/digitalRead().
Why?
Speed! Using this method allows for much faster I/O control, and we can control or read groups of I/O pins simultaneously, not one at a time;
Memory! Using this method reduces the amount of memory your sketch will use.
Once again I will try and keep things as simple as possible. This article is written for Arduino boards that use the ATmega168 or ATmega328 microcontrollers (used in Arduino Duemilanove/Uno, Freetronics Eleven/EtherTen, etc). My Arduino Mega is out at the moment, so I will update the tutorial for Mega users when it is replaced. This tutorial is not applicable to the Arduino DUE.
First, we’ll use the I/O as outputs. There are three port registers that we can alter to set the status of the digital and analogue I/O pins. A port register can be thought of as a special byte variable that we can change which is read by the microcontroller, therefore controlling the state of various I/O ports. We have three port registers to work with:
- D – for digital pins seven to zero (bank D)
- B – for digital pins thirteen to eight (bank B)
- C – for analogue pins five to zero (bank … C!)
Register C can control analogue pins seven to zero if using an Arduino with the TQFP style of ATmega328, such as the Nano or Freetronics EtherTen). For example:
It is very simple to do so. In void setup(), we use
DDRy = Bxxxxxxxx
where y is the register type (B/C/D) and xxxxxxxx are eight bits that determine if a pin is to be an input or output. Use 0 for input, and 1 for output. The LSB (least-significant bit [the one on the right!]) is the lowest pin number for that register. Next, to control a bank of pins, use
PORTy = Bxxxxxxxx
where y is the register type (B/C/D) and xxxxxxxx are eight status bits – 1 for HIGH, 0 for LOW. This is demonstrated in the following example:
// Example 43.1
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
// Digital 0~7 set to outputs, then on/off using port manipulation
void setup()
{
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void loop()
{
PORTD = B11110000; // digital 4~7 HIGH, digital 3~0 LOW
delay(1000);
PORTD = B00001111; // digital 4~7 LOW, digital 3~0 HIGH
delay(1000);
}
It sets digital pins 7~0 to output in void setup(). Then it alternates turning on and off alternating halves of digital pins 0~7.
At the start I mentioned that using port manipulation was a lot faster than using regular Arduino I/O functions. How fast? To test the speed of port manipulation vs. using digitalWrite(), we will use the following circuit:
… and analyse the output at digital pins zero and seven using a digital storage oscilloscope. Our first test sketch turns on and off digital pins 0~7 without any delay between PORTD commands – in other words, as fast as possible. The sketch:
// Example 43.1.1
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
// Digital 0~7 set to outputs, then on/off using port manipulation
void setup()
{
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void loop()
{
PORTD = B11111111;
PORTD = B00000000;
}
In the image below, digital zero is channel one, and digital seven is channel three:
Wow – check the frequency measurements – 1.1432 MHz! Interesting to note the longer duration of time when the pins are low vs. high.
[Update] Well it turns out that the extra time in LOW includes the time for the Arduino to go back to the top of void loop(). This can be demonstrated in the following sketch. We turn the pins on and off five times instead of once:
// Example 43.1.2
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
void setup()
{
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void loop()
{
PORTD = B11111111;
PORTD = B00000000;
PORTD = B11111111;
PORTD = B00000000;
PORTD = B11111111;
PORTD = B00000000;
PORTD = B11111111;
PORTD = B00000000;
PORTD = B11111111;
PORTD = B00000000;
}
And the results from the MSO. You can see the duty cycle is much closer to 50% until the end of the sketch, at which point around 660 nanoseconds is the time used between the end of the last LOW period and the start of the next HIGH:
Next we do it the normal way, using this sketch:
// Example 43.2
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
// Digital 0~7 set to outputs, then on/off using digitalWrite()
void setup()
{
for (int a=0; a<8; a++)
{
pinMode(a, OUTPUT);
}
}
void loop()
{
for (int a=0; a<8; a++)
{
digitalWrite(a, HIGH);
}
for (int a=0; a<8; a++)
{
digitalWrite(a, LOW);
}
}
And the results:
That was a lot slower – we’re down to 14.085 kHz, with a much neater square-wave output. Could some CPU time be saved by not using the for loop? We tested once more with the following sketch:
// Example 43.3
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
// Digital 0~7 set to outputs, then on/off using individual digitalWrite()
void setup()
{
for (int a=0; a<8; a++)
{
pinMode(a, OUTPUT);
}
}
void loop()
{
digitalWrite(0, HIGH);
digitalWrite(1, HIGH);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(0, LOW);
digitalWrite(1, LOW);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
}
and the results:
A small speed boost, the frequency has increased to 14.983 kHz. Hopefully you can now understand the benefits of using port manipulation. However there are a few things to take note of:
- You can’t control digital pins 0 and 1 (in bank D) and use the serial monitor/port. For example if you set pin zero to output, it can’t receive data!
- Always document your sketch – take pity on others who may need to review it later on and become puzzled about wchich bits are controlling or reading what!
// Example 43.4
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
// Fun with 8 LEDs on digital 7~0
void setup()
{
DDRD = B11111111; // set PORTD (digital 7~0)
// to output
}
byte a = B11111111;
byte b = B00000001;
byte c = B10000000;
byte e = B10101010;
void krider()
{
for (int k=0; k<5; k++)
{
for (int z=0; z<8; z++)
{
PORTD = b << z;
delay(100);
}
for (int z=0; z<8; z++)
{
PORTD = c >> z;
delay(100);
}
}
}
void onOff()
{
for (int k=0; k<10; k++)
{
PORTD = a;
delay(100);
PORTD = 0;
delay(100);
}
}
void invBlink()
{
for (int z=0; z<10; z++)
{
PORTD = e;
delay(100);
PORTD = ~e;
delay(100);
}
}
void binaryCount()
{
for (int z=0; z<256; z++)
{
PORTD = z;
delay(100);
}
PORTD=0;
}
void loop()
{
invBlink();
delay(500);
binaryCount();
delay(500);
krider();
delay(500);
onOff();
}
And here it is in real life:
Now to use the I/O pins as inputs. Again, it is very simple to do so. In void setup(), we use
DDRy = Bxxxxxxxx
where y is the register type (B/C/D) and xxxxxxxx are eight bits that determine if a pin is to be an input or output. Use 0 for input. The LSB (least-significant bit [the one on the right!]) is the lowest pin number for that register. Next, to read the status of the pins we simply read the byte:
PINy
where y is the register type (B/C/D).
So if you were using port B as inputs, and digital pins 8~10 were high, and 11~13 were low, PINB would be equal to B00000111. Really, that’s it!
Now for another demonstration using both inputs and outputs. We will use a push-wheel switch from Chapter 40 on our inputs (digital pins 8~11), and a seven segment LED display for output (on digtal pins 7~0 – segments dp then a~f). The following sketch reads the input from the switch, which returns 0~9 in binary-coded decimal. This value is then used in the function void disp() to retrieve the matching byte from the array “segments”, which contains the appropriate outputs to drive the seven segment LED display unit. Here is the sketch (download):
// Example 43.5
// tronixstuff.wordpress.com/tutorials > chapter 43
// John Boxall - October 2011
// inputs and outputs
byte segments[] = {
B01111110, B00110000, B01101101, B01111001, B00110011, B01011011, B01011111, B01110000, B01111111, B01111011};
// digital pins 7~0 connected to display pins dp,a~g
void setup()
{
DDRB = B00000000; // set PORTB (digital 13~8) to inputs
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void disp(int z)
{
PORTD = segments[z];
}
void loop()
{
disp(PINB);
delay(100);
}
And the ubiquitous demonstration video:
By now I hope you have an understanding of using port manipulation for your benefit. With a little effort your sketches can be more efficient in terms of speed and memory space, and also allow nifty simultaneous reading of input pins.
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.











































































