www.el
magazine.com emagazine
December 2014 | No. 456
CoCo-ri-Co:
Cool
Controller
Concept
mi
Wier lee)
Human Inte:
ig
CoCo-ri-Co: The Cool Controller Concept | T Board 28 Lowest-Power Exercising
Programmable Christmas Tree | varitab 402 (2) | ADS1115-eBoB | Arduino Software
Development with Atmel Studio | Infinite RGB LED Cube with Flowcode | Distance and Level Gauge
Improved Current Transformer | Red Pitaya | DesignSpark Tips & Tricks
Tantalum Bead Capacitors | Bulging Caps | Elektor.Labs goes wearable | GestIC &
3D TouchPad Workbook (1) | GM2308 Audio Signal Generator (1950/64) | Hexadokutor
© Projects
10 CoCo-ri-Co:
The Cool Controller Concept
A truly flexible, modular interface
for microcontroller projects. Forget
‘about switches, dials, displays,
LCDs—with the Elektor CoCo-ri-Co
> This isthe feet fourhundred and fifty-icth
‘edition of Elektor, a magatine that introduces a new
‘way of presenting electronics.
‘The Dutch edition of Elektor has been published for over #453 years and the
(German for over ¢43. very month #29:00¢ copies several terabytes find their way to rexier=
members ranging from enthusiastic amateurs to professional electronic engineers
‘Hlekaor’s dynamic and practical application of new electonic techniques has stimulated the
‘ever-present curiosity and imagination of engineers. Modern components, active and passive
and especially cheap digital and linear circuits, are used in practical designs. Many ofthe
circuits are developed in cur own laboratories, and cireit building is greatly facilitated by
‘using ready-made printed circuit boards we produce for the more important projects. [.]
“Elektor haz always tried to be dmamic and informative: but it can oocasionally irritate, a2
‘when it deflates technical imperiousness or indulges in humorous self-criticism that has given
‘ta British’ image on the continent.
‘We shall be working on the frst copies for 3975 2015 even as you ead this. Articles already
accepted describe an electronicelly-compensated:loudopenker system ARM controlled
“synthesizer stuglrquainy preampbifer an AVR controlled function generator, xramatogue
‘digital converter a LED replacement for 6-V moped lamps. gyraters Weird Components, and
‘farther developments of the mer-elock Platino,electronse-irem TBoard and SAPELPP. <<
Welcome back in 2014, Happy Reading,
Jan Bulting
Editor-in-Chief
Elektor International Media
The Team
Editor-in-Chief Jan Bulting
Publisher / President: Don Akkermans
Membership Menager: Raoul Morreau (all areas)
International Editorial Sta: Harry Baggen, Jaime Gonzalez-Arintero, Denis Meyer,
Jens Nickel
Laboratory Staff ‘Thijs Beckers, Ton Glesberts, Wisse Hettings,
‘Luc Lemmens, Mart Schroijen, Clemens Valens,
Jan Visser, Patrick Wielders
Graphic Design & Prepress: Glel Dols,
(Online Manager: Danielle Mertens
Managing Director: Don AkkermansGestIC & 3D TouchPad
WorkBook (1)
Raspberry Pi gets gesture control added
By Thomas Lindner Last month we introduced the Microchip/Elektor 3D Gesture Control dev kit and
& Roland Aubauer 3 Touchpad product bundle. Here we showcase the potential of the kit by con-
(Wicrochip GestIC® Team,
Germany) and necting the key component in the system, the MGC3130 GestIC® controller, to an
Jan Buiting (Elektor) RPI computer.
In response to introducing 1. What hardware
Microchip & Elektor’s Joint To be able to follow the project in an educational
exclusive offering of a prod- manner you need this hardware:
uct bundle consisting of the # Raspberry Pl Model B v.2, RBCAOOO
Hillstar MGC3130 3D Ges- 2x USB 2.0 3.5 watts
ture Control Development Kit Power supply:
as ol (dev kit’) and a ready to use micro USB 1200 mA SV for RPI
3D Touchpad, the most fre- # MGC3130 Hillstar Development Kit
MGC3130 Hillstar Single Zon«
Development kit | quently heard sighs and wishes
(Part # DM160218) were Iwant to connectit to my The final sensor system works independent from
‘micro! Followed by I want to the PC and just needs to be powered by @ USB
‘connect t to my PC! The offer charger or directly from the RPI. Communication
was announced last month [1] between the chips is established via the Ges-
and the hardware ison sale by _turePort pins provided on the little MGC3130
the time this article appears inboard in your Hillstar dev kit. A PC Is required
print (2). for parameterization and flashing the firmware
In this short WorkBook series to the MGC3130. A block diagram of the hard-
welll step-demo the case of aware configuration Is shown in Figure 1, and a
dedicated, mixed touch & 3D picture of the setup in Figure 2.
touchfree, controller for con-
nection to the Raspberry Pl 2. Connecting it up
‘comput, aiming eventually to The MGC3130 IC takes all the hassle out of capac-
play the “2048" game. It should itive sensing for 3 gesture control applications.
tenable the first wish to come The E101, E102, £103, £106, £107 signals on the
true—more to follow. hillstar’s MGC3130 board are connected to the
P| GPIO connector as pictured In Figure 3. Not
‘This being @ WerkBook, the idea forgetting Ground (GND) of course.
Is for You to get active with the
technology involved, so we'll 3. Parameterization with Aurea
use up-tempo notes and tech The MGC3130 allows East-West and North-South
scribbling. The information sup- hand flcks to be assigned to and flagged by its
plied here Is intended to spur EIOx pins. Aurea, the free graphic shell around
Ideas for hardware and soft- the GestIC controller, allows you to parameter-
ware development with the ize many sizes and configurations of planes that
MGC3130 chip for 3D gesture make up the capactive sensing pad to be call
control on any microcontroller brated and configured with high precision. The
system really. parameters for the GesturePort are pictured inFigure 4. Note the unique mix of 3D Gesture
(Flick EW; Flick NS) and Touch (Center).
4. Programming stuff
In terms of software, we will be using:
© OS: Raspbian (Debian Wheezy), version:
January 2014, release date: 2014-01-07
‘* Python version: 2.7.3 (default, Mar 18 2014,
05:13:23), (already installed on Raspbian)
‘© RPI.GPIO library version: 0.5.4 (already
Installed on Raspbian)
‘¢ Tkinter (already installed on Raspbian)
Leafpad text editor (already installed on
Raspbian)
‘© The code for the game ‘2048_with_Gesture_
Port_Demo.py’
The game proper will be discussed and url'ed to
you next month.
5. Quick Start
1. Install Raspbian on your Raspberry Pl.
2. Connect the Hillstar dev kit via USB to your
PC and start Aurea. There should be a small
popup window due to synchronization.
3. At the top side go to ‘Setup’ and then choose
‘Parameterization’.
4. Now click at the left side on ‘Extended’, browse
in ‘Parameters’ for the pre-configured file ‘Hill-
star GesturePort to Raspberry Pi Demo 2048.
enz’ and start the parameterization, which
takes a while.
5. After finishing, at the left side click on ‘Ges-
turePort’ and you see the configuration for the
events. If you click on ‘Flash’ in the upper right
comer the configuration shown in Figure 4 is,
saved in the MGC3130 chip.
6. Once flashed, the Hillstar dev kit runs in stand-
alone mode and you can connect the demo
with your RPi as pictured in Figure 1. It can
be powered either by an external USB charger
via the mini USB connector or you steal 5 V
from the Raspberry Pi.
Web Links
Hillstar MGC3130 Unit
Raspberry Pi
Next month GestIC & 3D TouchPad WorkBook
delves deeper in the demo and the 2048 game.
Meanwhile Elektor Lab notes on the GestiC devel-
‘opment kit and 3D Touchpad may also appear in
the Elektor. POST newsletter.
(140423)
[1] Add 3D Sensing to your Micro or PC. Elektor November 2014,
www.elektor-magazine.com/ 140408.
[2] Microchip Hillstar GestIC dev kit and 3D Touchpad product bundle:
www.elektor.com/microchip-dm160218-1
[3] www.raspberrypi.org/downloads/
istar-development-kit-and-dm160225-3d-touchpadBy Clemens Valens
(GiektorLabs)
CoCo-ri-Co:
The €@ol Controller GOncept
CS
at solving the perennial problem of adding
knobs, buttons and displays to microcontroller
designs without reinventing the wheel. I have
tried this before and faithful Elektor readers may
remember the J2B ARM Cortex-M3 board [1],
or ‘Platino’, the Arduino compatible, universal
Seite tee
‘© NXP LPCB12 32-bit ARM Cortex-MO+
‘All 48 MCU /0 pins accessible through
‘extension connectors
‘Up to 17 bicolor LEDs
'* Rotary encoder and/or pushbutton
Buzzer
‘© Supports TC, SPI/synchronous and
‘asynchronous serial communication
‘* ISP port compatible with 3.3-V FTDI USB-
serial cable (except 5-V supply)
Here is a new initiative in the quest for the ultimate human
interface in microcontroller designs.
Instead of the 210%” all-in-one solution
this time we resort to the modular
approach. The result is truly
flexible-it can even be used
as a (wearable) Christmas
decoration or for 3D
modeling.
‘Atmega board [2]. These two boards
offer a variable number of rotary encoders,
‘and pushbuttons together with a choice of LCD
sizes, the idea being that one of these boards
‘would satisfy the designer's appetite for controls.
‘This time I went for a different approach. Instead
‘of many controls that can be positioned in dif-
ferent ways, this project only has one. Instead
of one large versatile board that’s supposed to
contain everything, this design Is for a small
‘module that you sprinkle on or into your project
like salt on an egg. No more bulky hard-to-read
LCDs displaying cryptic messages in ugly fonts,
this time we stick to LEDs, Bright lights visiblefrom a great distance and blinking fast, slowly
or not at all is what we want; LCDs are uncool.
Compromises from the past
Many electronic devices are equipped with knobs
and buttons that allow its user to adjust one or
more parameters. Some of these controls do
not need a precise indication of the value of the
parameter they adjust. The volume control of
an amplifier is an example. When the sound is
loud (or soft) enough you simply stop turning
the knob. Other controls—function selectors for
instance—do need some indication to show their
position but the resolution is not too important.
A few LEDs are just fine in these cases. For con-
trols that allow precise adjustments a numeric
display is probably best.
Many applications use up/down pushbuttons to
replace rotary controls even though the latter are
faster and easier to operate. While it is true that
pushbuttons are small, cheap and easily handled
by microcontrollers, they remain a compromise
from the days that microcontroller resources
(memory, 1/0, processing power, etc.)
were expensive. Today this Is no longer
the case and we can throw lots of them
at simple problems without adding
much beyond one dollar to the
bill of materials. So why stick
Reinvent the
wheel
The design presented
in this article is revolution-
ary (pun intended) in offering
‘only one rotary encoder, up to 17
bicolor LEDs (i.e. 34 LEDs in total)
and a buzzer controlled by nothing less than a
32-bit ARM Cortex-M0+ based microcontroller
unit (MCU from now on). Overkill? Maybe, if you
only look at processing power, but clearly no,
also taking costs and interconnection potential
into account. The MCU I chose for this project
Is the LPC812M101JDH20FP, LPC812 for short,
featuring 18 1/0 ports, 16 KB flash memory, 4 KB
RAM, a good number of timers, an analog com-
parator, one 12C interface, two SPI controllers
and three asynchronous serial communication
Interfaces. What's more, thanks to an integrated
‘switch matrix, the pins of these communication
peripherals can be connected to any one of the
18 available 1/0 ports. This cool feature means
that it is possible to build a multi-protocol low-on-
wires communications port that can be configured
on the fly in software to talk either I2C, synchro-
nous (SPI or similar) or asynchronous serial. Add
pin and full duplex communication becomes a
reality. At a high-margin retailer's price of about
2 dollars apiece this clearly is a steal.
All components are mounted on a small circular
printed circuit board (PCB) with the MCU, one
LED and the rotary encoder in its center and the
remaining 16 LEDs arranged in a circle around
the encoder. At the edge of the PCB there Is a
ring of pinheaders for connecting the module to
other modules to create a control surface or to
wire it up to a host board.
Since there are only cool components on the
board (ARM Cortex-M0+ MCU, bicolor LEDs, rotary
encoder) it was baptized Coo! Controller Concept
or CoCo-ri-Co (the “ri” was added as a playful
hint at the French way of writing the rooster’s
call). BTW, if you look hard at the board you will
notice that it is hexagonal rather than circular.
Round Is cool, hexagonal Is cooler; this is how
(CoCo-ri-Co reinvents the wheel.
Who needs this?
The main application of the CoCo-ri-Co board
should be a digital potentiometer with instant
position indication. Any device or appliance that
could benefit from one or more rotary controls
to adjust its parameters Is a potential host to
‘CoCo-ri-Co. Think of volume and tone controls
in audio amplifiers, function selectors and speed
controls on household appliances, temperature
controls of heating systems or brightness and
color controls of lamps—all of these applications
make excellent hosts to one or more CoCo-ri-Cos.
Because it can communicate using serial, I2C,
SPI or custom protocols all through a single 3-pin
port, CoCo-ri-Co can easily be connected to host
applications that have a microcontroller inside.
For those applications that do not have their own
MCU, CoCo-ri-Co can be the main controller.
CoCo-ri-Co is small enough to fit in most enclo-
sures, even In wall-mounted junction boxes and
power outlets, and because of Its hexagonal shape
multiple boards can be tiled together to create a
control surface. As an example, think of a speedcontro! with dashboard for an electric vehicle
(Figure 1). One CoCo-ri-Co with encoder con-
trols as a speedometer, another—encoderless—
for displaying the battery level and a third might
show the number of revolutions per minute (RPM)
the motor is doing, or its temperature (or both).
But there is more.
‘Thanks to its size and low-power requirements,
(oh, did I forget to mention that?) CoCo-ri-Co can
be battery powered, from a 3 V button cell for
instance, making it portable and even wearable
(a geeky smart watch, anyone?). The bicolor LEDS
allow for decorative applications and it excels at
Christmas with its red and green looks and its
buzzer happily beeping away at Christmas carols
(see inset).
But that is not all.
I already mentioned tiling boards together to
create control surfaces, but these surfaces don’t
have to be flat. Indeed, you can create 3D sur-
faces from CoCo-ri-Co boards. The Cool Controller
Concept may be extended to include pentagonal,
‘square and triangular boards. With these shapes it
's possible to create so-called Archimedean solids,
you know, those highly symmetric, semi-regular
convex polyhedrons composed of two or more
types of regular polygons meeting in identical
vertices. Like the stitched soccer ball.
‘Such a ball, mathematically known as a truncated
Icosahedron, is composed of 20 hexagons and
12 pentagons. A soccer or Bucky ball made out
of CoCo-ri-Co boards (Figure 2) would be about
12 cms in diameter (25-mm vertex). Add a 3D
accelerometer and it can show LED animations
‘and play sounds depending on its position, speed
‘and movement. Now how cool is that? CoCo-ri-
Cool! I mean, totally cool.
What does it do?
Every time when the position of the rotary
encoder changes CoCo-ri-Co will send a value
(increasing or decreasing, depending on the
direction of rotation) on the communications
port (default: UART, 115200n81). This value lies
between two boundaries (0 to 100 by default).
‘The LED ring indicates the value as a bargraph
(default) or a dot, in red (default) or green. The
center LED can be controlled separately. Pressing
the pushbutton will produce a Key-Down message
and releasing it generates a Key-Up message.
‘The messages can have the following formats:
ASCII mode
© Rotary encoder: Bxxocxx, where 20000 Is
‘a S-digit field transporting values from
00000" to “65535”.
+ Pushbutton: Bx, where x = ‘0° (button
down) oF ‘1” (button up).
Binary mode
© Rotary encoder: Eyz, where the value is cal-
culated as 256 y +2.
Pushbutton: By, where y = 0 (button down)
or 1 (button up).
You can modify the behavior of the program on
the fly by sending commands to CoCo-r1-Co. This
allows you to change things like the color of the
LEDs, the boundaries of the encoder value or thedefault value). Every command req
‘Command —_|Data Deseri
LEDs
(0x00 (0) LED ring color: off | red* | green
LED ring mode: bargraph* | dot
[0x20 (32)
(0x02 (2) LED ring first LED (0*)
(0x03 (3) LED ring last LED (15*)
‘0x04 (4) LED ring direction: clockwise* | anti-clockwise
(0x05 (5) LED ring rotation (0*)
‘0x06 (6) LED ring LEDx on
(0x07 (7) LED ring LEDx off
(0x08 (8) O1t*12 (Centre LED: off | red* | green.
Rotary Encoder
(Oxi0 (16) [O*l Encoder mode: normal* | accelerated
Oxii (17) | 0-255 (0) Encoder minimum, low byte (0*)
(Oxi2 (18) | 0-255 (0) Encoder minimum, high byte (0*)
(0x13 (19) (0-255 (64) Encoder maximum, low byte (64;
0x14 (20) [0-255 (0) Encoder maximum, high byte (0*)
0x15 (21) [0-255 (0) Encoder value, low byte (0*)
x16 (22) [0-255 (0) Encoder value, high byte (0*)
Buzzer
Buzzer disabled | enabled*
(0x21 (33) 1 Buzzer beep now
(0x22 (34) [0-255 (232) [Buzzer beep frequency [Hz], low byte (232
(0x23 (35) | 0-255 (3) Buzzer beep frequency [Hz], high byte (3*)
[0x24 (36) 0-55 (64) Buzzer beep duration [ms], low byte (64*)
[0x25 (37) 0-255 (0) Buzzer beep duration [ms], high byte (0*)
Other
Oxfe (254) TO*]1. ‘Output mode: ASCIT | binary
OxfF (255) 1 Restore default values
encoder value Itself, the mode of the encoder, the
range of LEDs to use (default is 0 to 15). You can
also rotate the bargraph, produce a beep, etc.
At the time of writing this article I am still add-
ing useful commands, so please refer to the free
downloads for the complete list. Updates for this
project will be posted on Elektor.Labs [3]. Table 1
lists the currently implemented commands.
Configuration
One-time configuration of CoCo-ri-Co Is by means
of trimpot P1. Cofiguration consists mainly of
choosing the communications port type to use
(UART, SPI/synchronous or IC). With P1 you
can select up to 32 values in theory, but for
practical reasons—the precision of P1 being the
most important—this has been limited to eight
ranges. In Table 2 you can find which functions
Presenter eo oro err cere
Pe a enone econo ake rea
High (3.3 V), otherwise CoCo-ri-Co will boot into ISP mode.
UART, no parity, 8 data bits,
1 stop bit (n81)
/SPI/synchronous, Slave
address Oxib (29)
address Ox3a (58)
‘address 0x74 (116)
BC, Slave P4=SDA, PO=SCK (P12=IRQ)
ea] 5)>)9] >]are activated by a range. you want. Stay In the middle of a range, L.e.
‘The ranges are defined such that turning P1 to _away from range boundaries or you may expe-
Its minimum value selects UART mode, setting _rience random mode changes in the (near)
it in the middle gives SPI/synchronous and at its _ future.
maximum CoCo-ri-Co will talk I2C. A more precise 5. Switch off the board.
Figure 3. procedure Is available also and goes like this: 6. Remove the jumper between P6 and GND (con-
penance ae 1. Switch off the board. nector K5, pins 1 and 2}
(Co. The LPCBIZ ARM ; Bl )
CortexMO+ microcontroller 2° Fit @ jumper between P6 and GND (connector 7. Switch on the board and test.
has more than enough KS, pins 1 and 2).
braine ond muscle tetake 3+ SWitch on the board, Do not fiddle too much with P1 because It Is a
care of everything. 4, Adjust Pi to make the LED ring ight the range tiny and fragile device.
oe
§
e
E
e
ce
me
i
es
3
a
wv
e
:
:Note that the SPI/synchronous and I?C Slave
modes require the host application to poll CoCo-
11-Co on a regular basis. You could use a third port
to interrupt the host when new data is available.
Also note that real SPI Slave mode using the
MCU's SPI peripheral requires the SSEL signal. It
Is up to you to decide which port to use for this.
The “SPI” implemented uses the USART in syn-
chronous mode that can work without a SSEL
signal. If Slave mode doesn't suit you, be aware
that Master mode is available too (after some
programming).
Into the schematic
After introducing the board, its functions and
capabilities let's have a look at Its schematics In
Figure 3. Connecting 34 LEDs (bicolor, remem-
ber?) directly to 18 1/0 ports is hard if not impos-
sible, but when connected as two anti-parallel
4x 4 matrices (16 LEDs per matrix) they only
eat up 8 pins of our budget. These 16 LEDs form
the circle. This leaves one bicolor LED—positioned
in the center of the board—that must be con-
nected in another way. Little known, the LPC812
MCU I2C module supports two types of inter-
faces: ‘normal’ capable of using any 1/0 pin, and
‘dedicated’ insisting on using ports 10 and 11.
‘These two ports have high current sink capabili-
ties and are therefore great for controlling LEDs,
so I wired the remaining bicolor LED to these
ports. We will content ourselves with normal 12
for communication.
To limit the current through the LEDs resistors are
connected in series with them. Normally the red
and green LEDs would require different valued
resistors to obtain the same perceived bright-
ness (red usually being brighter than green) but
for the LED matrix this is not possible. It would
have been possible to do this for LED17, but for
convenience’s sake I only used one value resis-
tor on the board: 180 2.
For the rotary encoder I picked a model with
integrated pushbutton. Encoders without push-
button are about five times cheaper, but I like
the tum ‘n’ push way of setting parameters. The
pushbutton is hooked up to the MCU's Reset pin.
That may seem strange, but it makes sense once
you know you can disable the reset function on
this pin in software. During software develop-
ment you would normally keep the reset func-
tion available, but once the application Is finished
you can remove it. Or mount an encoder without
an integrated pushbutton. For those applications
requiring a pushbutton only, the PCB has a spe-
cial pushbutton footprint too, wired in parallel
with the encoder’s pushbutton.
‘The encoder is in the center of the board, on top
of LED17. Why? First, your application may need
‘only one of the two components, so you mount
only what you need. Second, we can have shaft
encoder lighting. LED17 allows you to use the
encoder shaft as a light guide (of course, you
will need an encoder with a transparent shaft for
this). The pushbutton footprint is also in the cen-
ter of the board but as far as I know the model I
chose does not come in a transparent package.
In any case, LED17 can produce a sort of cool
background glow of the control.
Many devices beep, or, as serious engineers would
say, they provide audible feedback. A module
presented as a universal control module must
have the possibility to do the same. Therefore a
footprint for a buzzer wasn’t forgotten. Due to
space constraints I had to use an SMD buzzer,
but unfortunately they can be pretty expensive.
A variable resistor P1 is attached to port PIOO_1,
which Is connected inside the MCU to an ana-
log comparator. This comparator can distinguish
between 32 levels that make it useful, for exam-
ple, as a 32-position switch to select different
software functions. It is mounted at the LED side
of the board for easy access (though it’s pretty
small). Do not mount P1 if you have no need for it.
‘The MCU does not require an external crystal or
oscillator because It has a good one built in. If,
you need a better clock you should wire it up to
PIO0_8 and PIO_9 but the board Is not equipped
with footprints to make this an easy job.
All resistors on the board have the same purpose
(current limiting) and value (180 2). They protect
most of the 18 1/0 ports, but not all. The two
‘SWD pins PIOO_2 and PIO0_3 are unprotected
50 as not to interfere with any debugging pods.
‘The LED matrix row pins are not protected either
because it Is unlikely for them to see any use
outside the board, and board space is limited.
Capacitors C1 and C2 provide power supply
filtering.‘Component List
Resistors
R1-R12 = 1800, SMD 0603
Pi» 100k0 trimpot, 3mm, e.. Bourns
TC33K-2-104E
Capacitors
C1 = 100nF, SMD 0603
C2 = 10uF 6.3v, SMD 0805
Semiconductors
ICA = LPCB12M101IDH20FP (TSSOP20)
LED1-LED17 = LED, bicolor red/green, Dial
‘ight 5988610207
Miscellaneous
BUZA = buzzer, Kingbright KMTG1102-AL
‘S2 = pushbutton, Multimec 3FTL6 ‘al (optional)
Extension connectors
The MCU also Is located in the center of the board,
but at the solder side with the resistors, capaci-
tors and buzzer. All of its 18 1/0 pins have been
routed to six 5-pin extension connectors, each
giving access to three I/O ports (6x 3 = 18) plus,
3.3 Vand GND. These connectors are not wired up
in a random way, but so that they have a useful
function. K1 and K4 for instance provide in-sys-
tem programing (ISP) capabilities. K4 is the real
15P connector (almost!) compatible with a 3.3V
FTDI USB-to-serial converter cable and K1 adds
the Reset pin to It. They are on opposite edges
of the board, 1.5 inch apart, so itis easy to con-
struct a more elaborate programming adapter on.
prototyping board if you would like to. Such an
adapter would probably have a 3.3-V regulator
on it to transform the 5 V from the 3.3-V FTDI
cable (yes, beware!) to 3.3 V. Actually, the Elek-
tor 110553 BoB-FT232R USB-to-serial adapter
[4]|s preferable to the FTDI cable because it can
provide the 3.3 V too.
K2 Is considered to be an analog port, because It
1s connected to the MCU’s analog comparator’s
‘S1 = rotary encoder with/without integrated Ready assembled module: Elektor Store #
pushbutton, e.g. Alps EC12E2424407
Ki-K6 = 5-pin pinheader, horizontal or verti-- Optional: PCB only, Elektor Store # 140183-
4140183-91, see wnw.elektor.com
4002.0)
Input 2 (-----ACMP_I2, PIOO_0 can be used as
Input 1). Together with PIO0_8 or PIO0_9 you can
Use it to create for instance a capacitive touch
sensor. If P1 is mounted you will have a variable
voltage on pin 2 of this connector.
3 provides access to the serial wire debug (SWD)
port of the MCU. It shares this port with the rotary
encoder but when in rest its contacts should be
open (if you use a model with detents and it is,
positioned between the detents). The pinout of K3
Is not conforming to any SWD pod standard that
T know of so you will probably need an adapter
of some sort.
KS Is intended for digital 1/0. Its pin 2 (PIO0_6)
has a current limiting resistor because this pin
is not SV tolerant (all the others are). The other
current limiting resistors are on ports that may
be frequently connected and disconnected.
6 Is the full-speed 12C interface, connected to
the pins 10 and 11 (and the center LED).
(Of course most ports on the extension connectors
are shared with the LED matrix and the other
Table 3. I/O ports In relation to extension connectors and functions.
PIO, K | Function PIO] K [Function PIO) K [Function
0 | 4 |RxD/Free 6 [5 [Buzzer 12 | 4 |ISP/Free
1 | 2 [Pi/Analog 7 [6 [Row 3 13 | 3 [Row 1
2_|-3 [SWOIO/sia & | 2 [Column i 14 | 5 [Column 3
3-3 [SWwcLWsiB ‘| 2 [Column 0 15 [1 [Row 0
4 [4 [txd/Free 40 |6_[tepi7R7FC 16 | 5 [Row 2
5 | 4 [Reset/Pushbutton a1 [6 [LEDI7G/PC 37 [4 [Column 2on-board peripherals so beware when you start
wiring the extension ports to all kinds of other
components. Table 3 summarizes the relations
between the I/O ports, connectors and functions.
From this table it Is clear that connector K4 Is
meant for communication with the host appli
cation. In ISP mode (i.e. when the MCU is reset
while PIO0_12 Is being held Low) PIOO_o and
PIO0_4 become a serfal port. In normal operating
mode these pins are free and can be assigned to
for instance the SPI or I2C module or to some-
thing else altogether. Once out of reset PIOO_12
becomes a normal 1/0 port. Note that PIOO_12
does not need a pull-up resistor because It already
has one inside the MCU (as do all the 1/0 ports,
except PIO0_10 and PIO0_11) so ISP mode will
not be activated accidentally when this pin is left
unconnected.
The project software
NXP has a website dedicated to the LPC microcon-
troller products [5] where you can find libraries
for all of them and which saves you the work of
creating the low-level hardware abstraction layer.
These libraries come in pairs, one for the chip
family itself and another for the evaluation and/
or demonstration board. Since this project uses
the LPC812 we need to look in the LPC8xx pack-
ages, and since we use the LPCXpresso compiler
tools (Figure 4) we have to pick the package
for this tool. The libraries are included (version
2.01) in the download for this article (6). I urge
to not replace them with freshly downloaded ver-
sions without doing an extensive file compare
first, because I have corrected some bugs in my
libraries that I have come across.
The LPCXpresso workspace for CoCo-ri-Co con-
tains two projects: Ipc_chip_8xx_Lib (the NXP
Figure 4,
The LPO(presso IDE used
to:develop the CoCo-ri-
Co software. Although
you cannat see it inthis
screenshot, the project
named Ip. chip_8xx fib is
also part of the workspace.Things to know about LPC812 1/0 ports
‘© In Table 3 the ports 10 and 11 are listed as IC without specifying a signal (SDA or SCK).
‘That's because it is up to you to decide which port carries what signal. See the Switch Matrix
section in the LPCB1x User manuel. These ports have open-drain outputs and should not be
used for fest SPI or UART modes.
‘© Ports 2, 3 end 5 default to their SWD and Reset function on power-up and must be
reconfigured in software before they can be used for other purposes. Pin Enable Register 0
controls these pins.
‘In digital mode all ports are 5-V tolerant except for PIO_6. Ports that can have analog
functions (PIO0_0, PIO0_1 end PIO0_6) become 5-V Intolerant when their anelog function is
activated.
«If the software disables the Reset input i is still possible to enter ISP mode simply by holding
PIO0_12 low while power-cycing the MCU (off-on)..
‘The LPCBIx family comes in several packages. On early versions of the 16- and 20-pin
packages the ISP mode entry pin was PIO0_1 instead of PIOO_12. If your MCU refuses to go
into ISP mode, check the revision code. It must be “4C* or higher for PIOO_12 to work.
‘© A virgin LPCB1x MCU boots directly into ISP mode so you should be able to program the MCU
at least once.
library) and 140183_cocorico_digital_poten-
‘tioneter (the real stuff). Both are included in
the downloadable archive that you can import in
LPCXpresso without unpacking It first.
The file nain.c contains the main engine
that reads the encoder and sets the
LEDs in a virtual matrix. In the back-
‘ground a 1-kHz systick timer takes care
of actually lighting the LEDs and
debouncing the rotary
rs _ encoder. Buzzer beeps
PNAS, are produced by yet
Bete ess another timer (the
aes Ae Multi-Rate Timer).
et To save program
= memory and
because they are
available the communi
cations are handled as much
as possible by the MCU's built-in drivers.
T encourage you to have a look at the source
code (in plain C) and play around with It. Copy
the digital potentiometer project to a new name
in the same workspace and modify it. It is not
too difficult I hope and comments are plentiful.
‘When you build a project it will create a HEX file
that you can program into the MCU using a serial
port and the Flash Magic tool [7].
CoCo-ri-Co Is available as a ready assembled
module from the Elektor Store. Bare PCBs are
also supplied for those who insist on an all-DIY
build at home or in the lab. Questions and con-
tributions can be posted on the Elektor.Labs page
of the project [3].
(140183:1)
Web Links
[1] J°B: Elektor September 2011,
‘www elektor-magazine.com/ 110274;
www elektor-labs.com/node/3832
[2] Platino: Elektor October 2011,
wwwelektor-magazine.com/ 100892;
wwwelektor-labs.com/node/2288
[3] CoCo-ri-Co on Elektor. Labs:
www.elektor-labs.com/node/4257
[4] Elektor 110553 Bo8-FT232R:
www .elektor.com/110553
[5] LPCOpen: www.lpoware.com
[6] Project downloads: www.elektor.
comy140183,
[7] Flash Magic programming tool:
www flashmagictool.comby Andrew Retallack
(Gouth Africa)
T-Board 28
Lowest-Power Exercising
Temperature Logger
beats Arduino hands down
With the Internet of Things increasingly driving MCU-based projects, power con-
sumption is becoming a critical element of any design. Every milliamp counts
when remote sensors need to run for months or years on a single battery.
Elektor’s latest T-Board 28 is perfectly placed to help you prototype your next
low-power project, as illustrated in this build of a power-efficient standalone tem-
perature logger. Put on your t-shirt!
‘The T-Board 28 [1] has a number of features
that give a designer the ability to optimize the
power utilization by tweaking the design and
then measuring the impact of these. This is one
of the key benefits to the T-Board over other
fixed platforms such as the Arduino. As many
first-time users of the T-Board will have made
the jump from an Arduino platform, I thought
It would be relevant to show my own experi-
mental approach using the T-Board 28 to pro-
gressively reduce the power consumption of a
temperature logger. The T-Board 28 comes with
an ATMEGA328 micro fitted, and is the largest of
the T-Boards series. The series and the t-shirt
are in the Elektor Store.
In order to become more familiar with ways of
reducing power consumption, I wanted to work
on a relatively simple project that would have
a practical use without distracting me from my
power-optimization goal. A temperature logger
was a perfect fit. The project was bullt to mea-
sure temperature at regular intervals using 2low-cost temperature sensor, recording these
‘on an EEPROM chip. When connected to a PC
(or a laptop in the field), the readings can be
downloaded over a serial connection. SD Cards
were considered in the initial design, but with
significantly higher power consumption (up to
3.5 times) and lack of tolerance for 5-V sup-
ply, It was decided to use EEPROM instead. At
a later stage the project could be enhanced
to include RF transmission of the readings;
power-optimization of RF Is of course a whole
‘other ball-game!
A quick look at the project design
{As can be seen from the schematic in Figure 1,
the design is very simple (a major advantage of
using a T-Board). A Microchip 24LC128P EEPROM
was connected via °C to a T-Board 28, with the
required pullup resistors on the I2¢ communi
cation lines. An LM6O temperature sensor was
selected due to its low-current drain, ability to
easily record negative temperatures (for those
readers and editors not lucky enough to live in
sunny South Africa!), and importantly its support
for voltage inputs starting at 2.7 V. Finally, an
LED was connected to give a visual indication of
the tasks the logger was performing. This helped
when measuring the power consumption, and
would of course be removed in the final version
of the logger.
The 241C128, as with all PC devices, has a device
address. This address can be set by tying pins 1,
2, 3 (AO, Al, A2) either High or Low. The 7-bit
address of the device starts with a fixed ‘1010
followed by the logic levels on pins A2 to AO.
For this design (with AO tied High) the address
is therefore 1010001. When you wire the chip
‘onto the breadboard, pay careful attention to all
pins—I spent hours debugging my code, only to
find I had tied pin 7 (the Write Protect pin) to
Vec instead of V;; (GND) effectively write-pro-
tecting the chip! Datasheets are easily misread.
Serial 1/0 (for debugging and producing a dump
of stored readings) Is carried out over the FTDI
pins of the T-Board, using the ATmega328’s,
built-in UART. An FTDI cable or module, con-
nected to the T-Board's FTDI connector, allows the
‘T-Board to be connected to a PC's USB port. Fur-
ther iterations of the design could include porting
the code to the T-Board 8, which would require a
software-Implementation of the Serial protocol.
The program code
The code was written using Atmel Studio 6.2,
the latest version of Atmel's in-house IDE. Sim-
ple modules were written to handle the ADC
(Analog-to-Digital Converter), TWI (Two-Wire
Interface), and UART functions. Here we need
to digress briefly to discuss terminology. Due
to trademarking around the [°C protocol, Atmel
have called their 12C-compatible protocol TWI.
It is 100% compatible with I2C, but Is just not
called I2C. Therefore in the datasheets and reg-
Ister naming you'll be looking for TW1, not I°C.
The code Is available for downloading at (7) It
should be straightforward to follow, however a
few notes may be needed for the compiler sym-
bols (accessed through the Symbols option of
the AVR/GNU C Compiler section of the project
properties). In order to calculate communica-
tion speeds and interval timing accurately, F_CPU
defines the CPU speed in hertz. System voltage
's defined in millivolts by SYSTEM_MILLIVOLTAGE,
to allow ADC readings to be correctly converted
into voltages. A DEBUG symbol exists that will
‘output debugging information on the serial port
if set to
When the MCU powers on, it first displays a sim-
ple menu over the Serial port to allow the user
Figures.
*Crcugran” of our exercise
aimed at geting T-Board 28
to draw as ite current
25 possible while acting as
2 fll blown Temperature
Logger.Pete iM
Fuse words are used by AVR microcontrollers to configure
2 range of functions / options. They need to be flashed by
‘an external ISP programmer, and once set they generally
‘cannot be modified by the program running on the AVR
(with a few exceptions).
They are often approached with great nervousness—and
sometimes rightly so as setting invalid combinations can
result in @ “bricked” (no longer functioning) MCU. To “un-
brick” the MCU, a special programmer is needed that
operates at higher voltages.
‘There are three fuses on the T-Board 28's ATmega328—high
fuse word (hfuse), low fuse word (fuse) and extended fuse
word (efuse). For our experiments, we will primarily alter
the fuses that determine the clock source for the MCU—the
Muse. AVR microcontrollers can run off a range of internal
and external clock sources, and we
need to use the fuses to configure
the MCU to use the ones that we
want.
In order to calculate the values of the
fuse words, you can wade through
‘some fairly cryptic datasheet text—
or use a fuse calculator. There are
‘a number of online ones (I like
the Engbedded one [4]) as well as
‘apps you can install on your tablet/
‘smartphone.
Setting fuses using a programmer
‘that is supported by Atmel Studio is
very straightforward ~ you simply
center the fuse values in the Device
‘Setting Fuse Words in Atmel Studio
Programming Dialog like so:
If your programmer is not supported natively by Atmel
Studio, then you will need to use AVRDude [5] to set the
fuses:
1. Open a command prompt and navigate to the folder that
AVRDude.exe is stored in
2. Enter the following to read the Fuse settings:
avrdude -c -p -U Lfuse:
3. Enter the following to program a Fuse:
avrdude ~c ~p -v -U
Lfuse:w:0xFF:m
where:
is AVRDude’s code for
the specific programmer you're using
(e.g. usbtiny for the USBTinyISP}—
refer to the file avrdude.conf for a list
of these;
is AVRDude’s code for the
specific MCU being programmed (e.g.
'm328 for the ATmega328);
“Lfuse is the fuse being
programmed—use fuse, hfuse or
fuse as appropriate;
OXFF is the value of the fuse being
‘set—change this as necessary.
Finally, if you want to experiment
‘more extensively with fuses, have @
‘search online, there are a number of
{good resources.
Timer2 is an 8-bit timer, so can only count up to a value of
255. Each clock cycle adds to the timer until it reaches 255
where it can be configured to generate an interrupt. As you
can see, if the Timer is running off a fast clock it won't take
long to reach 255 and generate an interrupt: a 1-MHz clock
will reach 255 after only 256 microseconds! Fortunately
there are @ couple of ways to slow the timer down. The
first is to use a prescaler that divides the clock speed down
further. The maximum prescaler available is 1024, which will
result in @ count of 255 being reached after 0.26 seconds.
‘An improvement, but still too quick.
Li: Bei
‘The second is to slow the clock speed down. We can’t
slow the main clock down, as we then aren't able to
‘communicate over the serial port reliably. Timer2 however
can work off an external crystal oscillator as well—in
asynchronous mode (asynchronous because the external
oscillator is not synchronized to the main CPU clock). The
Useful thing here is that very slow crystals can be used—I
used a watch crystal at 32.768 kHz. With this slower crystal,
the timer reaches 255 in 7.97 seconds, much more useful!
Additionally, a slower crystal of course uses less power.to print the log in comma-delimited format, or to
clear the log. The program waits for 10 seconds
to allow the user to make a selection, before
entering the normal logging loop.
‘There are two versions of the code: Version 1
(Figure 2) shows the completely unoptimized
code, while Version 2 (Figure 3) contains the far
more power-efficient version. The optimization in
the final version has been reasonably limited in
order to ensure the code remains readable and
easy to follow; there are certainly small addi-
tional power-savings that can be realized, and
Convert Reading to
Temperature
Write time &
temperature to
EEPROM
Flash LED 10 times
Initialization:
ART
™
EEPROM
yo Pins
Figure 2. Flowchart of “version 1”, the entirely palatable
‘but unoptimized firmware
Figure 3. Flowchart of ‘version 2", the F-Board 28
firmware optimized for current draw.The O;
imization Experiments
L, Estabteh 2 Basetine
Once the project is connected on a breadboard as set
‘out in in Figure 1, the T-Board Is initially configured in a similar
way to an Arduino Uno. The input voltage should be set at 5 V
using the voltage-selection jumper, and a 16 MHz external
crystal oscillator connected. As we need to measure the current
we'll remove the jumper completely and connect the DMM to.
the voltage-selection pins (black to the center pin, and red to
the 5-V pin). In this configuration the DMM needs to be tumed
to the Amps setting in order to complete the circuit.
Next, the fuses need to be flashed to the values in Table 1.
Finally, the “version-1" code (software download at {7])
needs to be loaded Into Atmel Studio, complled and then
flashed to the microcontroller. This version uses a simple
delay loop (implemented in the _delay_ms() function) to time
the delays between readings. The flowchart in Figure 2 gives
‘an overview of the code.
‘The initial set of measurements show a consumption of
‘approximately 12.4 mA while idle. From the code it can
bbe seen that the LED flashes 10 times before entering idle
state— measurements are taken once the DMM reading has
stabilized after these 10 flashes.
AA further single flash of the LED indicates that the temperature
reading is about to be taken and written to the EEPROM—
however the time taken to read the temperature turned out to
bbe too short to register a meaningful reading on the OMM.
Z__ Reduce the Input Voltage
The simplest optimization yielded the greatest savings.
‘Simply switch the voltage-selection jumper from the 5 V position
to the 3V3 setting, and the T-Board now operates off 3.3 V. In
‘our experiments of course we won't use the jumper, so switch
the red lead of the DMM from the 5 V pin to the 3V3 pin.
‘The code needs to be changed so that the temperature
calculations work off a reference voltage of 3.3 V; we need
to change the compiler symbol SYSTEM_MILLIVOLTAGE. To
do this, right-click on the project in the project browser and
sselect properties. Then, on the Toolchain tab, click on Symbols
under the AVR/GNU C Compiler section. Change the SYSTEM_
MILLIVOLTAGE from 5000 UL to 3300 UL (the UL ensures the
value is cast as an unsigned long). We then compile and flash
the new code to the MCU.
‘The measured current at 3.3 V reads 5.76 mA, a reduction of
6.6 mA: that simple change has more than halved the power
‘consumption of the logger!
Slow that CPU
3, 4, 5+ neem re eens
‘examine the impact of slowing the CPU down, using a
‘combination of swapping the external crystal oscillator
‘and dividing the clock speed. With each change made, the
‘compiler symbol F_CPU needs to be updated to reflect the
effective clock speed in Hz as listed in Table 2 (Note the
‘spaces in the F_CPU column are there for ease of reading
here, and should be removed when entered in Atmel Studio).
For each of the rows in Table 2, follow the steps highlighted
earlier: connect the programmer, update the fuses, change
the F_CPU in the code, compile and flash the code to the MCU,
disconnect the programmer and then switch the crystal if needed.
‘As can be seen there is a clear correlation between the CPU
‘speed and the current usage. Looking at the current usage at
‘500 kHz it looks like this is the path to choose. Unfortunately,
the ATmega’s USART is not able to reliably function at CPU
‘speeds as low 2s S00 kHz (refer to the datasheet as well as
[6] for useful BAUD rate accuracy calculator). So we need to
go back a step.
6 Use the Internal Oscillator
Next I looked at the impact of using the internal
oscillator at 8 MHz, and dividing by 8 to get an effective CPU
speed of 1 MHz. This speed is sufficient to achieve reliable
serial communications at low BAUD rates up to 4800—good
‘enough for the simple menu at startup. Once the LFuse
bits have been set to 0x62, the F_CPU symbol amended to
1000000UL, and the compiled program flashed to the MCU,
then the external crystal can be removed.
Current draw was now slightly higher than at the clock speed
of S00 kHz, but at 748 WA a great improvement on the
original 12.36 mA!
7 Disable BOD
‘The ATmega328 has a Brown-out Detector (BOD),
which allows a developer to guarantee consistent operation of
‘a project by putting the MCU into a “reset” state if the input
voltage drops below a specified level. However, this feature
‘comes at a power cost. By setting the EFuse we can disable the
BOD and squeeze those extra microamps out of the project. Set
the EFuse to 0x07 to disable the BOD, and you'll note a small
‘saving of microamps—not a large saving, but every bit counts.
8 Sleep
It’s now time to take a look at optimizing the code.
In the version 1 (Figure 2), we used a delay loop to time
the temperature readings. While it may seem like a delay
loop is not doing anything, the CPU is in fact spinning its
‘cogs counting the delay out. This of course uses power. Most
microcontrollers allow you to put them to sleep (effectively
turning the CPU and certain peripherals off) in order to save
Power, and then wake them up again when needed. Interrupts
are used to wake the CPU up—elther based on changes on
particular pins, incoming communications, or specific elapsed
time. The AVR is no exception, and has 6 different sieep
modes with differing levels of power saving. I won't go into
these in detail here, other than to say that I'll use the mode
called (imaginatively!) “Power-save". This mode allows us
to use Timer2 to wake the CPU up after a specific interval—
‘Timer2 being the only timer that can in fact wake the CPU.
In order to save on power and work with more manageabletimings, Timer2 Is set to run off an external watch crystal.
Refer to the text box “Timing the Timer".
‘To put this experiment in action, no Fuse bits need to be set.
‘A 32.768 kHz watch crystal needs to be inserted carefully in
the T-Board 28—these leads are very thin so make sure that
you don’t damage them, while at the same time ensuring a
‘900d contact with the header on the T-Board.
‘Then load, compile and flash the Version 2 code onto the MCU.
Version 2 does less flashing of the LED, just four flashes at the
tend of each temperature reading. I took my readings once the
current stabilized after the four flashes, and was delighted to
‘see a measurement of only 59 JA. This kind of current draw
should allow an 800-mAh battery to power the project for
nearly a year and a half. But there Is still more we can dot
©, Shut Down Unused Peripherals
= The ATmega328 has a register that allows you to
power off unused peripherals - the Power Reduction Regis-
ter (PRR). The function reducePower () disables the Timer0,
Timeri, SPI and the USART. The TWI and Timer2 are left
enabled as we need them to communicate with the EEPROM
‘and wake the MCU from sleep respectively. The ADC Is already
‘managed as part of the conversion process, so no further
‘optimization needed there. Additionally this function enables
the pull-up resistors on the unused pins to prevent them
from floating—floating pins can result in additional current
draw. With the DMM I was using I wasn’t able to see any
additional power saving from using these settings—looking
at the datasheet percentages it seems that the real saving
1s achieved when the CPU Is in active mode as the percent-
age savings are quite low.
nd
A Final
10. Change
‘After some comparison
to the datasheet I wasn't
happy with the power consumption
Twas achieving. Of course the
MCU isn't the only element drawing
‘current—the EEPROM and the
LM60 also have an impact. A few
‘quick tests, and references to thelr
datasheets, and I noted that the
EEPROM only draws 100 nA in
standby mode while the LM60 has
‘a typical quiescent current draw of
around 82 WA. By altering the circutt
‘so that the LM60 was powered off the
T-Board's PD7 (well within the pin's
‘maximum output current of 20 mA),
‘and modifying the code to power the
sensor only for the period needed to take a
reading, I managed to get the current draw
down to an incredible 1 yA (the lowest my
DMM could measure). After seeing this reading
T popped the champagne and considered the experimental
process a success! I took a few additional measurements, and
arrived at an estimated peak current draw of approximately
‘65 WA during temperature measurement. I rounded this up
to 1 mA for good measure, and then by calculating a few
averages I arrived at an estimated battery lifespan of six
‘years on an 800 mAh battery. Six years on 2 single battery Is
‘more than enough for our remote sensor.
Experiment | Description cpu mituivottace | LFUSE | EFUSE on
Tema Sv FEO SO lass
EES a oe
Se aoa a a
4 Use 4 MHz External Crystal 4 000 000 UL 3300 UL OxFD ox0S | 2.130
5 Divide Clock by 8 500 000 UL 3300 UL 0x7D oxos | 0.560
6 Internal 8 MHz oscillator + Divide by 8 _| 1 000 000 UL 3300 UL 0x62, 0x05 | 0.748
$—|aane oon tsoouno Uses ur —— [etfs
an a
ee creas ——|reoseso sara ——| nests
FS eS a — [tonto [soos — [estos fos
Experiment | Crystal Divide by 8? Effective clock speed F_cPU LFUSE Current
ee ee oe a
[ime — fre eo a
se —fe = a aDar ar ttestr98
aww teestr ing
send 3 m8 ay
User Se sends tO ayaa even tee 102
wait WRITE = we nee
vice Aaarest Seagrass
17 send me S00 cep OEE I
result = 120 con 8) .
xo cand f pingacess MO
j1send Newory
ceation ADHTeSS
Web Links
[2] Atmel Studio: www.atmel.com/atmelstudio
[1] T-Boards 8/14/28, Elektor September 2014, wonw.elektor-magazine.comy 130581
[3] USB Tiny: www.crash-bang.com/using-usbtiny-with-atmelstudio/
[4] Fuse Calculator: www.engbedded.com/fusecalc/
[5] AVRDude: http://savannah.nongnu.org/projects/avrdude
[6] Baud Calculator: www.wormfood.net/avrbaudcalc. php
[7] Version 1 & 2 download: www.elektor-magazine.comy 140413
1 challenge readers to take it further and share
their thoughts on www.elektor-labs.com and
http://forum.elektor.com (Topic: Microcontrol-
lers & Embedded).
T-Board helps with optimization
In order to reduce current consumption on a
‘microcontroller project, there are (at a basic level)
four common areas to focus on. The first Is to
reduce the input voltage, resulting (simplistically)
In a physical illustration of Ohm’s Law. The sec-
‘ond Is to reduce the clock speed
inet condition
> ay
EEPROM FIRST ADORESS
resutt = 12¢-sen¢ reat $608 LU) scges LH
vy vacation nsress, 2 (Ee ope I!
11 5end Meme end (uint® EEN
result = 120
of the CPU, as less clock cycles per second result
{n lower current draw. The third is to put the CPU
Into a sleep mode when It isn’t needed. Finally,
disabling unused peripherals and components
will result in further reductions in power.
‘The T-Board 28 has been designed with the flex-
ibility to help with the first and second items dis-
‘cussed above: the ability to select input voltage,
and a means to switch out crystal oscillators to.
change the CPU clock speed. The second and
third Items are implemented in the pro-
ye veegram code. Finally, the voltage selector of the
‘T-Board acts as useful point to measure the cur-
rent usage in order to assess the effectiveness
of the optimizations.
In addition to the items outlined above, a number
of other efficiencies can be gained—for exam-
ple more efficient coding, which results in fewer
lock cycles to achieve specific tasks, will reduce
the current requirements. As discussed earlier,
the code efficiency has not been a focus of this
project—optimizing your coding in C/C++ isa
whole series of articles on its own!
Measuring the current consumption
It Is assumed that many readers using the
‘T-Board (Including myself) may not have access
to 2 fully kitted lab. Therefore I used a rela-
tively crude, but nevertheless effective, means of
measuring the current usage—a low-cost digital
multimeter (DMM). The DMM was switched to
measure amps, and the probes then connected
(using female connectors) to the voltage-selec-
tion header pins on the T-Board. This allowed me
to measure the current usage of the T-Board at
point in time. The positions of the jumpers in
the circult Isolate the draw of the project, and
are not impacted by the power supply circuitry.
In order to measure the current more
accurately, I desoldered and removed
‘the power-indicator LED as I found
Its current draw far outweighed that
of the MCU Itself. This also reduced the
consumption sufficiently at higher levels
of optimization to enable me to switch
my DMM to the A setting, allowing me
to better measure the Impact of some of
the smaller changes.
Of course the limitation with this measurement
method (apart from a reduced level of accuracy)
is that the current Is only measured at a point in
time. Ideally one would like to record the mea-
surements over time in order to calculate an
average current draw (this Is in itself a useful
project to include in a future edition of Elektor).
This is where the LED connected to PBO came
In useful as an indicator of the activity of the
program, and therefore a context to the current
being measured.
The experiments
‘The spread on the previous pages of this article
focus on the experiments carried out to reduce
current draw, detailing what changes were made
and the measured impact of these. In order to
implement each of the progressive optimizations,
these steps were followed:
1, the ISP programmer was connected and any
changes to fuses made;
2. any changes to the code were compiled and
flashed to the T-Board;
3. the ISP programmer was disconnected;
4. any physical changes to the circuit were made;
5. a 9-V battery was connected to the 2.1-mm
Jack and the current measured with the DMM.
Any FTDI cables/boards should not be connected
when the measurements are taken.
The results of the various experiments are sum-
marized in Table 1, along with the changes made.
Before we get started, @ quick note on the pro-
grammer: Atmel Studio [2] supports a number
of ISP programmers natively, which require lit-
tle or no special configuration. There are also a
number of other programmers (usually available
at a lower cost) that are not natively supported
but can be configured to work under Atmel Stu-
dio (eg. USBTiny, USBasp, etc.). Apart from the
flashing of the program onto the MCU, a key
difference Is the way the fuses need to be set
(Refer to the text box “Don’t Blow Your Fuse” for
more information). There are various resources
online explaining how to configure Atmel Studio
to support these third-party programmers [3].
Next Steps
I found this process enormously helpful, and it
really highlighted to me the benefit of a flexible,
lean & mean platform like the T-Board. Overall,
consumption was reduced from an Arduino-class
12.3 mA to an average of 13 WA (averaged based
on time spent in sleep vs. active mode); a reduc
tion of 99.89%!
I challenge other readers to take this to the next
level—perhaps migrating to the T-Board 8, or
Including an RF sensor to transmit the readings.
Either way, with your t-shirt on.
(140613)Programmable
Oates nat- ae ha
Brings (blue) light into the darkness
eee Co) So
osmeatheen lesions * proaching rapidly. So it has become
Deon Ce aoe ek
Vi Cec
ba al unusual mood lighting for the
YA eee ete eee eee’
Pee es
oS
Ceo rT
sorts of beautiful pat-
PeeteElectronics hobbyists are always keen to make
a festive gadget for the celebrations around this
time of the year. Not something read-built from a
garden center or home improvement store, but a
circuit which has something special and that you
can’t just buy anywhere. Over the years Elektor
have published numerous Christmas circutts, the
majority of them projects that contain a number
of LEDs which provide the ambiance.
This year, in conjunction with the printed cir-
cult board manufacturer Eurocircults, we have
designed a very nice circuit for you, which you
can bulld yourself of course if you have the time
and inclination, but we also offer this Christmas
tree ready-bullt in the Elektor web store for an
attractive price, You can always tell your visitors
that you soldered the teeny-weeny SMD compo-
nents in the little tree yourself with the ald of a
microscope and a very small soldering iron during
the annual Christmas function at your work...
The Iittle Christmas tree that you see here is pro-
vided with no less than 62 bright blue LEDs on
the front that, with their color alone, will already
generate a pleasant Christmas atmosphere. The
control electronics is on the back, mainly com-
prising a powerful microcontroller. True, we have
had other flashing Christmas trees in our maga-
zine before, but this particular specimen has an
‘extensive light show built in, which causes all Kinds
of patterns or texts to ‘run’ across the LEDS. A
number of patterns have already been pre-pro-
‘grammed, but a great feature is that you can very
easily design your own pattems and effects using
your PC and then simply store them in the mem-
ory of the Christmas tree via the USB connection.
Powerful microcontroller
‘An ARM Cortex-MO microcontroller from STM has
been used for controlling the LEDs (see the sche-
matic In Figure 1). This relatively cheap 32-bit
Figure 1
‘The schematic for the
Christmas tree mainly
consists of a microcontroller
‘and 62 blue LEDs.Figure 2.
‘The circuit board is double-
sided and screened on
the front with a so-called
PCB-Pixture solder mack [1]
depicting snowflakes.
(60% of re ste)
Component List
Resistors
RI-RIG = 62-1000 (SMD 0805)
RA7-R24 = 1009 (SMD 0603)
R25-R2S = 10kQ (SMD 0603)
Capacitors
C1,C2 = 10uF 6.3V tantalum (SMD A)
C3°C9 = 100nF 40 ceramic (SMD 0603)
Semiconductors
LED1-LED62 = LED blue (SMO 1206)
1-94 = FOV304P (SoT23)
ICL = STMa2F042Cs (LOFPA8)
IC2 = W2SQ80BVSNIG (508)
ICG = LO1117833TR ($0223)
Miscellaneous
USBI = micro USB connector, PCB mount
(47346-0001)
‘SW1 = pushbutton, PCB mount (TACTB-64K-F)
PCB (files only) # 140371-11
microcontroller offers, besides much computing
ower, an integrated USB2.0 interface. This allows
for a very easy connection of the microcontroller
to a PC. Thanks to the built-in bootloader its very
straightforward to download new LED-patterns
or new firmware. In order to provide the user
which a generous amount of space for patterns
or animations of their own design, a serial flash
memory with a capacity of 1 MB (8x1 Mbit) Is
‘connected to the microcontroller. This may appear
‘small compared to the typical size of memory
sticks and memory cards these days, but nev-
ertheless provides sufficient space to store more
than 90,000 complete LED patterns.
The LEDs are driven in a 4x16 matrix (not
entirely, 3x16 + 1x14). Therefore 16 (14) LEDS
are driven alternately by port pins PO through
P15 of the controller. The four columns are con-
tinually multiplexed. Because of the persistence
of vision of the human eye, this fast switching is,
not noticed and It appears that all the LEDs are
‘on continuously. The LED columns are switched
by four P-channel MOSFETS of the type FDV304P.
‘The cathodes of the LEDs are connected via cur-
rent-limiting resistors (R1 through R16) directly
to the port output pins of the microcontroller.
‘This saves a large number of components, but we
do have to take into account that the maximum
Ce et ea
Ce et eetotal current that the microcontroller can handle
{Is only 80 mA, which therefore means a max\-
‘mum current of 5 mA per LED. If we use LEDS
with sufficient efficiency then they will still be
very visible in a reasonably bright environment.
The entire circutt is powered from the micro-USB
connection. A 3.3-V regulator (IC3) provides a
regulated power supply voltage for the micro-
controller and the LED matrix.
Figure 2 shows the printed circuit board design
for the little tree. The LEDs are on the front, the
remaining components including the micro-USB
‘connector are on the back. For this occasion the
circuit board Is screened with a PCB-Pixture sol-
der mask [1] depicting snowflakes.
For those of you who are keen to etch the circuit
board yourself and populate it with components
we feel obliged to warn you that some of these
‘SMD components are difficult to solder by hand!
The source- and hex code files are available from
the Elektor website [2]. The ARM software is writ-
ten in C using the Kell compiler. The largest part
of the code is related to the USB communications
and this is based on the ST firmware library.
The bootloader mode will be activated when the
pushbutton on the back is pressed while the tree
Is connected to a PC. It Is then possible to down-
load or update the firmware with the ald of the
ST software DfuSe [3].
Software
By default, the ready-built Christmas tree from
the Elektor shop Is already provided with a wide
range of animations. If you are happy with those
then there Is nothing more you need to do. If,
however, you would like to create your own pat-
terns, animations or running texts and whatever
else you can come up with then we direct you
to a special interactive web page that we have
bullt for you where you can indulge yourself
[4]. This page contains a picture of the Christ-
mas tree with all its LEDs. You can make your
‘own animations by using your mouse to click
the LEDs on the screen on or off. This way you
create a pattern, where you can also select the
desired duration and brightness. All generated
patterns appear at the bottom of the screen
next to each other. There is also the possibility
to enter a scrolling text (text symbol at top left).
In this way you can build your own animations.
You can store an animation for later use. Using
the preview button you can view the animation
on the screen.
Program your own animations and win!
Cee eee ea ea
ee eat
an
Seen
a eee
ee aoe:
Cee ena
ee Cen
Perea
en
Pee Seana
2015—winners will be notified personally.
You can make multiple of these animations and
‘thread’ these together into one long light show.
Once that is done you can download the entire
sequence to the Christmas tree.
‘The tree is connected to a PC using a micro-
USB cable. When you do that for the first time
Windows will install a driver. Windows recog-
nizes the little tree as a HID peripheral. After
that you can ‘flash’ the new animation to the
tree from the web page.
For use in the living room you can connect the
tree to a 5-V wall adapter which Is fitted with a
micro USB cable.
Enjoy and many happy returns.
Figure 3.
‘The components mounted
on the back ofthe Christmas
Web Links
[1] www.eurocircuits.comYblog/171-PCB-PIXture-launched
[2] www.elektor-magazine.com/ 140371
[3] www.st.comy/ web/en/catalog/tools/FM147/CL1794/SC961/$S1533/
PF257916
[4] www.eurocircuits.com/x-masVariLab 402 (2)
Control and display board
By Ton Giesberts (Elektor Labs)
The control portion of the VariLab power
supply uses a microcontroller to set the
desired output voltage and current and
to measure all significant voltages and
We designed a
separate control board to con-
figure and monitor the output of the VariLab
power supply board described in the previous
issue and display the output voltage and current
‘as well as other data. Its main components are an
‘Atmel ATxmegal28A4U-AU microcontroller and
‘an LCD module with four lines of twenty char-
acters. The microcontroller has onboard ADCs
‘and DACs for setting and measuring the output
voltage and current, so the component count
‘can be kept relatively small.
Circuit description
‘As you can see from the schematic diagram (Fig-
ure 1), the circuit is built around an ATxmega
microcontroller (IC1). The balanced supply volt-
‘ages for the entire circuit (#5 V) are taken from
the supply board. The microcontroller operates
from a 3.3 V supply voltage, which Is provided
by voltage regulator IC3.
All measurement and control signals are present
‘on connector K3. The circuit also receives the
necessary supply voltages through this connec-
tor. The sense signals for the output voltage and
‘current of the supply board are fed to the ADC3
currents in the circuit. All measurements
and settings are shown on a four-line LCD
module. Naturally, there is also a USB
port for communication with a PC.
‘and ADC4 inputs of the ATxmega, with the cur-
rent sense signal first buffered by IC2d. Resistor
RS is dimensioned so that the range of the sense
signal for the power supply output voltage is vir-
tually the same as the measuring range of ADC3.
‘The voltages Vsmps’ and 48Vin are also routed
to the control board and measured by ADCS and
‘ADCS. Resistor R6 Is dimensioned to apply 5%
of Vsmps’ to the ADCS input so that the input
signal level remains within the measuring range.
Diodes D2-DS protect the ADC inputs against
overvoltages and negative voltages.
‘Two signals are necessary to set the output volt-
‘age and maximum output current of the power
supply: 0-4 V for the voltage and 0-2 V for the
current. The reference voltage for the ADCS Is
provided by an external 2.5 V reference source
{(IC6, for which we chose the old standby LM336)
because the internal reference voltage of the
‘microcontroller is not sufficiently accurate. The
reference voltage can be adjusted precisely with
1, but this trimpot can usually be left at its max-
imum setting because the calibration can also
bbe done in software. The output voltages of the
DACs are amplified by a factor of 2 by a pair of
‘opamps (IC2A and IC28), which in theory yields‘a maximum control voltage of 5 V.
‘A disadvantage of using the internal DACs is that
the output range does not extend all the way to
OV (the data sheet states a minimum value of
0.15 V). Since we definitely want to be able to
adjust the output voltage down to 0 V, an offset
voltage of 0.3 V Is applied to the two opamps
to ensure that the control voltage range on the
‘opamp outputs can start at 0 V. The 0.3 V offset
voltage Is derived from the 2.5 V reference volt-
‘age by R11/R12 and buffered by 1C2c.
For the opamps we chose a Microchip MCP6004-E/
SL quad device, which features rail-to-rail inputs
and outputs. This IC Is powered from +5 V and
-0.6V (the latter via 08) because its maximum
rated operating voltage is 6 V. This arrangement
allows the output voltage to be adjusted all the
way down to zero.
The four-line LCD module is driven in 4-bit mode
by the ATxmega. The display Is powered from
5 V. Although the logic high level of the drive sig-
nals from the microcontroller is only 3.3 V, that
Is adequate for reliable operation. The display
contrast can be set with P2. The microcontroller
can switch on the display backlight via T1 when
a jumper is fitted on JP3. Since the voltage reg-
tlator on the supply board that provides the+5 V
supply voltage does not have an extra heat sink,
It Is not advisable to leave the backlight on all
the time. In the current version of the firmware
the LCD Is only illuminated when current limit
ing Is active. The backlight can be permanently
disabled by removing the jumper at JP3.
A pair of rotary encoders with built-in pushbuttons,
(S1 and $2) and a separate pushbutton ($3) are
provided for the power supply operator interface.
‘The separate pushbutton can be used for several
functions, including quickly switching the power
supply on or off. By default the output voltage is
set with S1 and the output current is set with $2.
Figure 1.
‘Schematic diagram of the
contral and display board.
All ofthe measurement
{and computation tasks are
handled by an ATkmegat28
‘microcontroller.
J
J
tr
sarnerouscatrouci|
ostnctnnccenttinsomnescy
ne eneiaaas|
im
‘Aamo 20ANUAUComponent List
Resistors
Default 0.125W, SMD 0805)
RI-R6,RG,R14,RI6,R22-R25 = 1k 1%
RS = 2.87kO 1%, O.1W
L.BOKA 1%
10MR 1%
10k0 5%
Rio = 8209 1%
Figure 2. Rid = 8.870 1%
The component layout of the | Ri2 = 1.21K0 1%
double-sided control board. | R43 = 1.30k0 1%
RLS = 150 1%, 0.25
Ri? = 100 5%
18,20 = 2.240 5%
Ri = 470.5%
R21 = not fitted
RDG = 33K0 5%
RI7 = 56K 5%
PI = 5008 10%, 0.5W, 25-tum preset, top
adjustment (Bourns 3296Y-1-SO1LF)
P2 = 10kR 20%, 0.15¥, preset, top adjustment
Capacitors
C1,C2 = 229F SOV, 5%, SMD 0805 COG/NPO
C3..C9,C13 = L00F 25, 10%, SMD 0805 X7R
C10 = 10UF 63V, 20%, diam. 6.3mm, 0.1" pitch
C11 = 100uF 25V, 209%, diam. 6.3mm, 0.1” pitch
C12 = 4.7UF 6.3V, 10%, SMD 0805 tantalum (case R,
AVX TAJRE7SKOOGRNJ)
Inductors,
L1,L2 = 3309 © 100MHH, 0.089 1.78, SMD 0603
Semiconductors
Di = LED, red, 3mm, wired
1D2,03,D4,05 ~ BAS70-04 (SMD SOT-23)
D6 = PRTRSVOU2X (SMO SOT-143B)
7,08 = TS4148 RY (SMD 0805)
Ti,72 = 8C817-25 (SMD SOT-23)
Ici = ATkmegai28A4U-AU (SMD TQFP-44),
programmed, Elektor Store #120437-41)
1C2 = MCPGOO4 (SMD SOIC14)
IC3 = KF33RDT-TR (DPAK-3)
ICA = 4N25 (DIP-6)
ICS = LM35 (10-32)
C6 = LM3362-2V5 (70-92)
Miscellaneous
Kt = USB connector, type B, PCB mount, wired,
vertical model (Lumberg 2411 01)
K2 = 6-pin (2x3) pinheader, 0.1" pitch
KS = 14-pin (2x7) pineader, 0.1" pitch
Ka = 2-way screw terminal Bock, 0.2" pitch
KS,K6,1P4 = 3-pin pinheader, 0.1" pitch
K7 = 4-pin pinheade, 0.1" pitch
3P1,302,1P3 = 2-pin pinheader, 0.1* pitcn
jumpers for 31,12,3P3,3P4
$1,S2 = 18PPR rotary encoder with integrated
Pushbutton (e.g. Alps EC1iE183440C)
3 = pushbutton, PCB mount (€.9. Multimec
RASFTLS)
3 = cap for pushbutton, h=19mm (e.g. Mutimec
1503-19.0)
B21 = piezo buzzer, 1.5-16 Voc, max. 8 mA, diam.
‘4mm, 7.62mm pitch
Xi = 16MHz quartz crystal, C, 18pF; dim. § x 3.2mm.
(Abracon ABM3-16.000MHZ-B2-T)
LCD1 = 4x20 characters, with bacight, Elektor Store
#120061-73
pce # 120437-2Buzzer B21, which is driven by the microcontrol-
ler through T1, generates an acoustic signal in
situations such as current limiting. Indicator lamp
LED D1 Is lit when the power supply output Is
enabled. Temperature sensor ICS measures the
temperature In the enclosure, which can be dis-
played on the LCD. The sensor is located directly
on the PCB, and when the board Is installed as
Intended in an enclosure the sensor Is close to the
heat sink on the supply board. For other applica-
tions the sensor can also be mounted somewhere
else and connected to the board by a few wires.
There is also a galvanically isolated output (IC4)
avallable for switching purposes, although this
capability is not used in the current version of
the firmware.
USB port for connection to a PC Is additionally
present. This can be used to send measurement
data to the computer, or the voltage and current
can be set from the computer with the ald of a
terminal emulator program. The USB port is nor-
mally connected directly to the microcontroller
over 3P1 and 3P2, but if desired it can be fully
Isolated by removing these two jumpers. Diode
D6 protects the microcontroller against potential
overvoltages on the USB port. Voltage divider
R26/R27 Is included to prevent the microcontrol-
ler program from hanging if the USB connection
Is suddenly broken.
The microcontroller can be put into programming
mode (ISP or PDI) by fitting a jumper on JP4.
POI Is usually the better option, and it Is also
supported by the Atmel AVRISP mkII program-
mer. With both settings the microcontroller is
programmed over connector K2.
The voltages Vset, Iset and ground are present
on connector KS for convenient measurement
during calibration. If the control board Is used
in a project other than the VariLab power sup-
ply, the balanced +5 V supply voltages for the
control board can be connected to K6. The max-
imum current consumption is +50/-5 mA with
the backlight off or +105/-5 mA with the back-
light on. Finally, K7 provides access to a num-
ber of free 1/0 pins of the microcontroller (PAO,
PAL and PA2).
Construction
The PCB layout shown in Figure 2 Is compact
and just big enough to hold the four-line display
module, the rotary encoders and the pushbutton
(see also Figure 3). Components are mounted on
both sides of the board. Most of the components
are on the component overlay side, Including all
of the SMDs, connectors and leaded components.
The only components mounted on the other side
are the pushbutton, the two rotary encoders, the
vertical USB connector and the Indicator LED,
and of course the display module.
Be sure to use the components shown in the
components list when assembling the board.
Substitutions are not allowed. The comments in
Figure 3.
Top and bottom sides of
the fuly assembled control
board. All of the controls
‘and indicators, including the
LCD module, are located on
the same side,Figure 4.
The LCD module is secured
to the PCB by a pair of M3
screws and nuts, with extra
ruts forthe right spacing.
the previous article (for the supply board) about
‘mounting the SMDs also apply here: you need a
certain amount of experience in order to solder
these devices properly by hand. If you do not
have sufficient experience, we recommend that
you do not start on this project or that you get
help from a more experienced electronics enthu-
slast or technician,
‘Mounting the components on the side with the
encoders, pushbutton and display module is eas-
ler because they are all conventional compo-
nents. Use short wire bridges or a 16-way pin
header to mount the LCD module a few millime-
ters above the PCB, so that It cannot touch any
protruding wires on the control board. Secure
the LCD module to the PCB with M3 screws and
nuts in the two holes at the bottom edge of the
module. A pair of nuts between the module and
the PCB provide exactly the right spacing (see
Figure 4). Screws are not necessary at the top
edge of the module, since the connecting wires
or the pin header provide the right spacing and
firm attachment.
Once all the components are mounted, you can
fit jumpers at positions P1 and JP2 for the USB
ort, 3P3 for the LCD backlight, and P4 for PDI
programming mode. Now the board Is ready for
use with the supply board.
Use a short 14-lead flat cable to Join connector
3 to connector K3 on the supply board. Keep
this connection as short as possible to avoid inter-
ference. No other connections between the two
boards are necessary. Actually you don’t have to
Join the boards together just yet, since we plan
to tell you how to mount the boards In a sult-
able enclosure in next month's Issue of Elektor.
{As usual, there are two options for program-
ming the microcontroller. You can order a prepro-
grammed microcontroller from the Elektor Store
(item number 120437-41; see [2]), or you can
rogram the microcontroller yourself from Atmel
Studio after you assemble the board. For the
latter option you need a sultable programmer,
such as the Atmel AVRISP mkII, connected to
programming connector K2. As usual, the source
‘code and hex files (120437-11) can be down-
loaded free of charge from the web page for this.
project [2].
Next month we will tell you more about the firm-
ware, fitting the boards in an enclosure, and
power supply calibration and adjustment.
(140373)
Web links
[1] www.elektor.com/ 120437,
[2] www elektorcom/ 140373
[3] www.elektor-labs.com/120437‘By Martin Ossmann_
(Germany)
Figure 1.
‘The Red Pitaya module is
very compact.
Figure 2.
Block diagram of the Red
Pitaya module.
Red Pitaya
Not just a USB scope module
Red Pitaya is the first open-source instrumentation platform that can be confi-
gured for various measurement tasks. Ready-made apps are available on the
Web for downloading, but you can also program your own specific measurement
processes. Several potential measuring tasks and demo programs are described
in this article.
To get an idea of what the module (Figure 1) can
do, have @ look at the block diagram in Figure 2.
The central component is a Xilinx 2C7Z010
system-on-chip (SoC) device. It contains a dual-
ea
“SH
‘core ARM9 processor clocked at 800 MHz, which
hosts a Linux distribution on the Red Pitaya board.
The SoC also contains an FPGA with 28k logic
cells, a bunch of block RAM (BRAM), and several
DSP slices. The FPGA can be used to implement
functions, such as the functions used in digital
signal processing, for extremely fast execution.
The SoC Is surrounded by a variety of peripheral
devices and 512 MB of RAM.
There are two 14-bit A/D and D/A converters for
measurement tasks, with a maximum sample rate
of 125 MS/s. with those specs you can handle
signal conversion for fairly demanding tasks, and
the FPGA gives you the necessary processing
speed. The board features an Ethernet port, a
USB Host port and a USB Com port for easy
‘communication with a PC over a serial interface.
There is also a slot for an SD card, which the
Linux OS used for mass storage Instead of a hard
disk drive. General purpose 1/0, IC, RS232 and
‘additional relatively slow A/D and D/A converters,
‘can be accessed through extension connectors.
In short, the module has everything you need
for demanding measurement tasks and high-
performance signal processing with relatively
high-frequency signals. That's exactly what Red
Pitaya Is supposed to be: a general-purpose
Instrumentation platform for signals up to 50 MHz.
Getting started
Getting started does not present any problems
because a good user guide Is available on the
website, Simply copy all the software and data
that is supposed to be on the SD card to a
MicroSD card and insert It in the card slot on the
Red Pitaya board. Then connect the Red Pitaya to
your LAN and switch on the power. The moduleboots up automatically, and you're ready to go.
You might want to monitor the boot process on
your PC via the USB Com port, since that way
you can see which IP address Is assigned to the
Red Pitaya. After the module has booted up,
you can communicate with Linux directly over
the USB Com port or you can use Ethernet for
further communication. The latter is the preferred
method.
Instruments from the Bazaar
One of the main objectives of the Red Pitaya
project is to provide ready-made applications in
the form of apps available online. You can find
the apps in the Red Pitaya Bazaar. After you point
your web browser to the Red Pitaya website, you
can go to the Bazaar from the home page and
select the application you want. The apps listed
in Table 4 are currently available,
Of course, many other interesting apps for various
‘measurement tasks are likely to show up In
future. All of the projects are open source, so
You can use them as starting points for developing
your own applications.
We chose the oscilloscope and spectrum analyzer
apps to get familiar with the device. We used
them to make measurements on the circuit shown
In schematic form in Figure 3 and in physical
form in Figure 4.
‘The Inputs of the Red Pitaya A/D converters are
buffered by opamps with 1 M& input impedance,
's0 you can connect normal scope probes directly
tothe inputs. You can select a measuring range of
2 Vpp OF 20 Vpp by setting the input gain jumper.
If you run the oscilloscope app on the Red Pitaya
and connect the probes to TP1 and TP2 of the
cuit in Figure 3, you will see the screen shown
in Figure 5. All of the usual oscilloscope settings
are available.
When you run the spectrum analyzer app, the
screen shown in Figure 6 Is displayed. You can
track and compare the two spectra in real time.
In Figure 6 you can easily see the harmonics of
the crystal oscillator, with stronger harmonics on
‘P1 at the gate output than on TP2.
After getting an Initial impression of what can
be done with the Red Pitaya platform, we looked
at what you need to know in order to program
applications for this device (Figure 7).
Web-based instruments.
The A/D and D/A converters usually interface
directly with the FPGA. The FPGA Is also used
© Two-channel signal generator,
(0-50 MHz
© Two-channe! oscilloscope,
2x 125 MS/s
BER OP es eR a ee
* Two-channel spectrum analyzer
'* Frequency response monitor
© PID controller
Figure 3.
A aystal oscillator circuit.
Figure 5.
‘The Red Pitaya scope app in
action.
Figure 6.
‘The Red Pitaya spectrum
‘analyzer app in action.Figure 7.
The components involved
ina Red Pitaya web-based
Instrumentation app.
Figure 8.
Block diagram of the signal
‘generator.
Figure 9.
Block diagram of an FM
‘generator consisting of two
DDS stages.
o
NS
for any required pre-processing, such as storing
frames in Its fast internal memory. This means
that you have to write suitable code to program
the FPGA.
The FPGA usually communicates with a program
running on the ARMS processor. In most cases
this program handles the control tasks, which
do not require high processing speed but are
‘more complex. Naturally, this code also has to
>be generated for any new application. In the case
of a web-based app, this code is linked in on the
Linux web server as a shared library. The web
server handles data transfers between the web
browser on the client system and the program
‘running on the ARM processor. The graphical user
interface (GUI) on the browser Is implemented
using a language such as JavaScript. Here again,
this code must be developed for a new app.
‘As you can see, you need to know a good deal
about programming if you want to develop
‘complex instrumentation apps. However, you can
take advantage of the fact that all existing apps
for the Red Pitaya are open source, so there Is
plenty of starting material you can use to work
your way toward a solution by making small
changes. Now let's see how you right get started.
Programing the ARM processor
First let's look at what you can do with simple
software for the ARM processor in combination
with existing FPGA code. The standard FPGA
code includes functions for a two-channel signal
generator. The waveform for each channel Is
‘generated using a lookup table stored in memory
with a total of 16,384 samples. Samples are taken
from the lookup table incrementally in the same
way as a direct digital synthesis (DDS) signal
generator. These samples are fed to the 14-bit
D/A converters. The sampling rate is 125 MHz.
The block diagram for one channel is shown in
Figure 8.
The configuration parameters are stored in FPGA.
registers, which can be read and written by the
processor at specific addresses. This is done by
aC program.
FM RTTY signal generator
‘Suppose you want to shift the frequency of the
signal generator back and forth under software
control. To do this, you change the step size of
the DDS signal generator. The result Is an FM
RTTY signal generator. The wait time between
‘each change Is 20,000 1s, which corresponds to a
data rate of 50 bits per second. The two transmit
frequencies can be set to any desired value
between 0 and 50 MHz. In the demo software
the bits to be transmitted are first calculated
‘as Baudot code and then output in a loop. The
program code for this loop is shown in Listing 1.
You can directly modify the FPGA register by
simply accessing the variable chb-count-step.
This example shows that with a bit of simple
of C programming, you can implement truly
interesting applications with the Red Pitaya. Of
course, you have to generate the C code using a
complier that is compatible with the ARMS CPU.
For this purpose the author used the ARM9 GCC
compiler running under Lubuntu on a virtual
‘machine under VirtualBox.
‘Another option is to generate C code for the
Red Pitaya under Windows, for which good
descriptions are now available. In that case you
can use SCP/WINSCP or another suitable utility
to download the code from the PC to the Red
Pitaya and then run the program,FPGA programming
‘The next step is programming the FPGA, for which
‘we also have demo software. The author used the
\Vivado tool from Xilinx, in the form of the free
|WebPACK edition, to generate the FPGA software.
‘The standard FPGA code for the Red Pitaya is
also available as a Vivado project, so you can
Use it as a starting point for your own designs
by modifying the original code. In particular, that
saves you the effort of reinventing the interface
to the ARM processor and the other hardware.
It Is also helpful that FPGA register contents and
signal samples can be viewed as variables in ARM
processor memory. This enormously simplifies
‘debugging because you can peek into the FPGA
‘while it is running. Now let’s look at an actual
application,
FM signal generator
‘We already have a two-channel signal generator
in the FPGA, with each channel arranged as shown
In Figure 8. Now we want to modify this so that
‘one channel modulates the frequency of the other
channel. Since the waveform of the modulating
signal Is also stored in memory, you can use
the device as a sweep generator by making the
modulation linear.
Figure 9 shows the block diagram of our
FM signal generator The upper portion Is the
modulator DDS. The samples in the table have a
‘word size of 32 bits to enable smooth frequency
modulation. The samples read from the table are
sent to the second D/A converter for monitoring.
Modulation is performed by sending the samples
to the adder of the second DDS in the lower
part of the figure, which forms a modulated DDS
‘oscillator. To allow an oscilloscope to be triggered
‘when the signal generator Is used in sweep mode,
suitable trigger signal Is tapped off from the
upper DDS. It is routed to GPIO pins and to a
software-readable register.
‘The essential software for the modulator shown
in Listing 2 consists of a few declarations and
‘a code block with six instructions.
Figure 10 shows the spectrum of the output
signal obtained by using this FM signal generator
to produce a 10 MHz signal modulated by a 1 kHz
sine wave with a specific modulation depth. The
modulation depth is set to produce a frequency
deviation of #2 kHz on the 10 MHz carrier
frequency.
The Verilog code of the frequency modulated
oscillator is very similar to that of the modulator
(see Listing 3). One of the main differences is
{in the computation of the new sample position,
since the modulation signal data fmInput—1 Is
also added here.
Listing 1. RTTY transmit loop.
uint32_t delay1=20000 ; // 50 Bit/sec
whiLe(1)
for(int k=O ; kenBits 5 kr+){
ant theBit=biteuffer[k] ;
‘41f(theBIt){ g_awg_reg->chb_count_step
else{ g_awg_reg->chb_count_step
usleep(delay1) 5
?
?
step2 5
step ; 3
Listing 2. Verilog code of the DDS modulator.
reg [ 32-1: 6] dac_buf [@:(1<<14)-1] ; // data buffer
16384x32 Bit
reg [ 32-1: 8] dacrd — ; // DAC value
reg [ 14-1: 0] dac_rp J] DAC read pointer
reg [ 32-1: 0] dac_pnt ; // read pointer
always @(posedge dac_clk_1) begin
dac_rp <= dac_pnt{é-1+1
dac_rd <= dac_buf{dac_rp] ; // read data value
signal_o <= dac_rd 5
dac_o Open Object File For Debugging.
‘The compiled files generated by Atmel Studio are
located in the following folder under Windows 7:
C:\Users\,000\AppData\Local\
\Witicro\Arduino\Butlds\SpeedTest\
ardutno_due_x_dbg\
There you will find the file speedrest.e1£. Now
let's open it for debugging.
If the sketch was compiled and saved with the‘Arduino IDE, a copy of this file Is also located in
the debug folder for the sketch. It can be seen
In the Solution Explorer window of the code gen-
eration instance of Atmel Studio under “Output
Files’ (Figure 8).
Using the browse function, find and select the out-
put file Speedrest..elf. You should see a window
like the one shown in Figure 9. You can specify
your own project name and storage location for
the debug project folder. Your settings will be
saved and used automatically the next time you
open the debug project.
Next you see a window for selecting the device
family and target microcontroller (Figure 10). For
the Arduino Due you should select “SAM3, 32 bit”
for the device family and “ATSAM3X8E” for the
microcontroller type.
‘Now the file Speedrest..cep appears in the Solu-
ton Explorer window. This is simply the program
file of the sketch, which originally had the exten-
sion . ino, Right-click the project name “Speed-
‘Test_Debug” to open the Properties window.
When the Atmel ICE is connected to the PC over
USB, the debugger can be selected under Too! ->
‘Selected debugger/programmer. Here you must
specify “SWD" as the interface instead of “JTAG".
Now the Atmel ICE Is ready. You can also use it
as a programmer. To open the programming win-
dow, press Ctri-Shift-P or cick the chip symbol
with the lightning flash. The desired functions
are available after you click Apply. You can set
the maximum SWD clock rate (2 MHz) on the
Interface Settings tab. On the Memory tab, you
can download the speedtext.e1f file directly
to the flash memory of the microcontroller. The
program starts running automatically after the
programming process completes.
However, it Is more efficient to use the Debug
~ Start Debugging and Break or the Start With-
‘out Debugging command (or the corresponding
icon: the blue arrow with the vertical blue bar or
the solid green arrow) to download a program
for debugging or running, instead of the device
programming function.
Downloading the complete program to the micro-
controller takes roughly 1 second with the Atmel
ICE, which is quite fast.
‘The actual structure of the downloaded Arduino
rogram can be seen in the Solution Explorer win-
dow, where the main. cop file is selected and the
‘cursor is positioned on the first line of this routine
Figure 9,
Dialog for selecting the
‘generated output fil.
Figure 10.
Dialog for selecting the
device family and device
type.
Figure 11.
‘The true complexity of an
[Arduino project can be seen
{inthe Solution Explorer
window.
Figure 12.
When ths error message
appears ater you modiy 2
fle, simply cick “Reload” to
dismiss the message.Figure 13.
Oscilloscope screenshot
of the 150-kH pulse
waveform,
Figure 14.
Microcontroller PIO register.
Figure 15.
Oscilloscope screenshot of
the 12-MHtz pulse waveform
generated by version 2.0 of
the program.
3 re
Deron corte GF)
(Bicrenraps race ape =)
(Cina ered eat ot)
‘Great roataens cote Os)
31
rea rostoeps cern 2)
= Qiiswntnnten coe BU
* Ohecimeass on
Saree mera
eres
Sree teers Saxe
= Brose
* Broren
Cima.
+ nos
preertimetr
eda eat:
ameas Gaal
od
nae one
sees nee
Sees Sem
(Figure 11). As you can see, the speedrest..cop
file is only a small part of the overall program,
which is why a full compilation takes so tong.
The debugger gives you access to all the debug
functions of Atmel Studlo, such as single-stepping
with F11, setting breakpoints with F9, defining
breakpoint conditions in the Breakpoint window,
and s0 on,
If you edit and recompile the speedtest..1no file
in the first instance of Atmel Studio, the mes-
sage shown in Figure 12 appears in the second
Instance (the debug environment). Press “Reload”
to close the debug message and load the mod-
ified program into the microcontroller. Now the
cursor Is again positioned on the first line of the
program code and the program can be run again.
If you have previously worked with 8-bit AVR
microcontrollers in the Atmel Studio environment,
you will not have any problems working with
32-bit ARM microcontrollers because the user
Interface is nearly the same. Incidentally, clearing
and rewriting the flash memory with the Atmel
ICE does not affect the boot loader because It
Is located in the ROM of the microcontroller and
therefore cannot be deleted or overwritten. Con-
sequently simply downloading a program over the
USB interface still works the same way.
SpeedTest
Only the following two instructions are executed
in the main loop of the example sketch (see the
SpeedTest listing):
digitalwrite(TP1,1);//0n
digitalwrite(TP1,0); //ort
With an oscilloscope, you can see a pulse wave-
form on this pin while the program is running,
with a pulsewidth of 2.35 ps and a period of
6.6 Hs (Figure 13), which corresponds to a fre-
quency of about 150 kHz. That is not very high,
and you could hardly be blamed for thinking that
there's no reason to use an ARM controller clocked
at 84 MHz for this when a simple 8-bit AVR micro-
controller can do it better.
The reason for this poor performance is that the
Arduino instruction digi talwes te is @ cover name
for a bunch of C routines, as you can see by exe-
cating the program in single-step mode with the
debugger (F11 key). To actually achieve high
processing speed, you have to avoid this over-head. Fortunately, the Arduino programming language Is not
a separate language, but instead a form of C with a GNU
compller in a special Arduino configuration.
This means that a pin configured as an output can be
addressed directly by setting or clearing a bit in the PIO
register. The Instruction
const int TPl =
//Test pin
selects Arduino pin 7 as the test pin. According to the Arduino
pin mapping, this corresponds to pin PC23 of the microcontrol-
ler or bit 23 in the parallel input/output (PIO) register. With
the program stopped you can go to the 1/0 View window of
the debugger (Figure 14) and click bit 23 of the PIO_ODSR
(set) register to set the pin high. To reset the pin, click the
same bit in the PIO_CODR (clear) register. In the main loop
you can simply use the instruction
PIOC->PIO_SODR = 1<<23;
to set the pin without any fuss or bother.
To test this, and at the same time check whether conditional
compilation works properly, the author generated a new ver-
sion of the sketch (see the SpeedTest 2.0 listing). If the
expression Direct Is defined in the code, the code segment
after #1fdef Direct Is compiled, and otherwise the previ-
ous version with the slow digi talwrite instruction is com-
piled. Naturally, this change would also work in the normal
Arduino IDE.
Listing 1. Speed-Test.
[RRR RRR EERE REE
//Speed-Test with Arduino Due
[oR aae aR Ra REA Ea
const int TPL //Testpin
void setup()
{
[+ add setup code here +/
// set the digital pin as output:
PinMode(TP1, OUTPUT) ;
}
void Loop() {
// put your main code here, to run repeatedly:
digitalwrite(TP1,1); //on
digitalrite(TP1,0); //Aus
?Listing 2. Speed-Test 2.0.
[[eeeeteeeesneanannneanannanannnees
//Speed-Test 2.8 with Ardutno Due
/[[eeeetenenenennannnnaennnaneennees
include yarduino.n«
“
“
const int LED1 = 13;
‘Aint LED2 = 12;
‘ant LED3 = 11;
ant TPL = 7; //Testpin
define Direct
void setup()
t
/* add setup code here +/
J/ set the digital pin as output:
inode (LED1, OUTPUT) ;
inode (LED2, OUTPUT) ;
inode (LED3, OUTPUT) ;
pintode(TP1, OUTPUT) ;
// set output tow
digitalwrite(LED1,0);
digitalwrite(LeD2,0)
Gigitalwrite(LED3,0)
Gigitalwrite(TPL,0)5
void Lo0p()
// put your main code here, to run repeatedly:
#fder Direct
//x= state of PIO_SODR with bit 23
‘Ant x = PIOC->PIO_SODR | 1<<235
wntle (1)¢ //Omly for testpurposes, don‘t exit thts Loop
PIOC->PIO_SODR = x;
PIOC->PIO_CODR = x;
?
else
digitalwrtte(TP1,1)5
digitalwrite(TP2,0) 5
fenatt
?
‘The result of this code optimization, as shown
in Figure 15, is stunning: the pulse waveform
now has a pulse width of 23.2 ns and a period
of 83.3 ns. This corresponds to 12 MHz ~ about
80 times faster than before. From that we can
conclude that using an ARM microcontroller isn’t
such a bad idea.
Summary
Working with Atmel Studio accelerates Arduino
sketch development to a completely new level
thanks to shorter turn-around times, since only
modified code Is recompiled. Atmel Studio and
the tools that can be used with it, such as the
‘Atmel ICE as a debugger and programmer, are
worthwhile when you work with Atmel microcon-
trollers because they offer professional debugging
features and because downloading programs to
the microcontroller memory is significantly faster,
Incidentally, you can also use Atmel's SAM ICE
instead of the Atmel ICE for ARM projects. With
the SAM ICE hardware debugger and program-
‘mer, microcontroller programming speed can be
boosted by a factor of 4 because it can operate
at 8 MHz Instead of 2 MHz. For this you need
the adapter described in the inset. Ifyou are a
professional software developer, the expenditure
Quickly pays for itself even ifthe device can only
be used with the AT91xx microcontroller family.
(1303924)
Web Links
[1] Atmel Studio 6.2:
wwew.atmel.com/microsite/atmel_studio6
[2] Arduino IDE for Visual Studio:
wwew.visualmicro.com
[3] Atmel ICE:
www.atmel.com/tools/atatmel-ice.aspx
Review: wwnw.elektor-magazine.com/ 140275
[4] SAM ICE:
www.atmel.com/tools/atmelsam-ice.aspxby Thijs Beckers
(Glektor Labs)
Bulging Caps
The other day I went to the local Used Chemicals
Drop-off to dispose of some sad old inkjet print-
ers when a fairly intact looking PC case caught
‘my eye. Without needing to dumpster dive I was
able to spot an “Intel Core™ 2 Duo” sticker and
another with the Windows Vista™ Home Premium
‘OEM product key, these gave me a clue about the
‘age of this PC. It wasn’t beyond hope considering
that my current laptop was “Built for Windows
Vista"—I'm reluctant to throw away stuff that
still works, even though it might not be shiny
and brand new anymore. Anyway, the PC case
didn’t look battered or kicked around much, so
I decided to take it home and to find out about
the specs—CPU, RAM, HDD, that sort of thing
Back home I opened it up. All components were
present except for the hard drive. And tt looked
like the previous owner had removed it decently
‘and hadn't just ripped It out. So I guessed it was
time to try to fire it up,
I connected a monitor and hooked up a key-
board and mouse. I connected the power cord
‘and pushed the Power switch on the front and.
It came alive! I entered the BIOS to see more
detailed specs and was happily surprised. Here's
‘a breakdown of my find
© CPU: Intel Core 2 Duo £4500 @ 2.2 GHz
© RAM: 2 GB DDR2 @ 667 MHz
© Mainboard: Fujitsu D2151-A21
© Graphics: NVidia Geforce 8400GS 256 MB
‘© Optics: DVD-ROM and DVD-R/RW DL drives
© 350-W PSU
«Internal Card Reader
© Cooler Master case
In 22 months we will have a good laugh about
this configuration, but these days It’s good
‘enough for casual surfing, mailing and even some
music making. Some more dumpster-diving in
certain places Is sure to yield a hard drive and I
can get this baby running.
But first there was an issue I didn’t like very
much. I noticed it when I inspected the main-
board. See those capacitors next to the ATX con-
nector? Though the mainboard functioned per-
fectly, my electrical engineering hunch says them
‘caps look like they're about to explode. Which Is
of course a bad thing. But if replacing a couple
of bulging capacitors is the only thing needed
to give this PC a second lease of life, I'm still a
happy camper. I ordered a couple of decent low-
ESR type replacement caps (Panasonic FM-se-
ries), removed the time bombs and soldered the
new caps in.
After Installing a fresh operating system, the PC
ran fine. And after a month or so it still does. Did
I mention I made a Hackintosh out of it? Maybe
I shouldn’t have said that out loud ©.Elektor.Labs goes
wearable
by Clemens Valens
(Glektor.Labs)
Wearable is the new hype
‘The previous months have seen a lot of hobby-
{st-related activity from Intel, the world’s largest
manufacturer of PC microprocessors. Not only
did Big Blue release their new Galileo (V2 is now
available) and Edison boards with Arduino sup-
port, the company was also the main sponsor of
the above mentioned Rome Maker Faire. At this
show Intel made another announcement, besides
the Edison board, that didn't really get the atten-
ton that it deserves, in my humble opinion: Intel
firmly intends to become a major player in the
still pretty small wearable electronics market.
To prove this they showed of their MICA (My
Intelligent Communication Accessory) bracelet.
4
Intel has invested in start-ups and teamed up
with fashion designers to come up with refer-
ence designs (and products, why not?) to open
the market and to show what's possible besides
displaying the user’s heart rate and body tem-
perature. Have a look at the Mimo Baby Monitor,
built on Edison.
Elektor cannot stay behind, of course, and so
here's a call for wearable electronics projects to
be published on Elektor.Labs. Have you designed
something wearable? Do you have an idea for
such a device? Post your wearable ideas and
projects on Elektor.Labs and we will see that the
best ones will be transformed into real products.
.elektor-labs.com/wearable
3D printing—the story continues
‘Some months ago In this column I ranted about
the useless things produced by so many people
with 30 printers. I ended the article by suggesting
that those people should print their own 3D
printer filament or “ink” to save the planet
from drowning in polymer 30 printed gar-
bage. At the Maker Faire that was held at
the beginning of October 2014 in Rome
and that I visited I encountered once more
many useless 3D printed objects. To be
honest there were some very useful 3D
printer applications on display too, sadly
they were a small minority.
During the keynote presentation the win-
ners of a product design contest orga-
nized by the Italian magazine Focus got
‘announced. To my big surprise the win-
ning project was a... 3D Printer Filament
Extruder! A kind of 30 printer that prints
3D printer ink. Being an Italian project,
great attention had been given to Its looks,
and the result is an appliance that sure
looks great in any kitchen (unlike the ugly
30 printer). At the top you feed in poly-
mer ingredients and out comes a filament
that gets collected on a detachable spool.
Very likely it’s sultable for making spaghetti too.
Walking the show grounds I came across a few
other similar machines, but not so nicely shaped
‘as the EWE Filament Extruder. Photos are avail-
able on this webpage:
www.elektor-labs.com/3¢-printing
(140365)by Neil Gruending
(Conade)
DesignSpark Tips & Tricks
Day #16: Working with Components
We've talked a bit about components in
the previous installments so today let’s
look at them in more detail.
Tw oe oe tee De eo
46 ABE oe
6
a
a
ia
°
a
4)
A
BBX
Today I realized that we've talked about com-
ponents in DesignSpark before without dis-
cussing them in detail or how to use them
efficiently, so that will be our topic for today.
Back in DesignSpark Tips & Tricks Day #3 (Elek-
tor September 2013) I talked about libraries and
how components in DesignSpark linked all of the
design information for an electrical component
in one place. That’s how the schematic and PCB
tools can find the component information they
need without interfering with each other.
Creating and editing components
‘Creating and editing components can be a lot of
‘work if you draw them from a blank page every
time. If you can find a similar component that’s,
already in the library then it’s easiest to copy It
using the “Copy To” button in the Library Man-
‘ager window and then modify it. But when you
‘can't, then the DesignSpark component wizards
‘are a great way to make new components quickly.
Let's bulld an audio playback IC component to
see how the wizards work.
always like to start with the schematic symbol
first so we will open the DesignSpark schematic
wizard by clicking on the Wizard button in the
Library manager. Answer a few questions and It
will automatically create simple schematic symbol
that we can modify. After alittle editing I came
Up with the schematic symbol in Figure 1. The
pins are where I want them but if you look closely
‘you can see that they have the default names N1
to N16 which Is okay for now because they will
be changed later at the component level. One
Useful trick that I used is to place temporary text
strings over the pin names to make sure that
the proper pin names will fit inside the symbol.
DesignSpark also has a PCB footprint wizard that
can create a wide variety of PCB footprints for you.
‘The best part about itis that it can create all of the
pads for you along with the correct spacings. The
last step Is to use the component wizard to asso-
diate the schematic symbol to the PCB footprint.
‘Once you choose the schematic symbol and PCB
footprint you've just created you will get to the
‘Assign Pins screen lke in Figure 2 which is where
you can label each pin name and associate the
‘schematic symbol pins to the PCB footprint. In
my case I designed the schematic symbol so
that its pin numbers match the PCB footprint
pin numbers so I would click the “Assign 1-to-1"
button, But DesignSpark would let you have any
pin mapping you want. This Is also where you
‘can enter all of the pin names in the Terminal
Name column. Clicking on the Next button will
create the component for you and let you save
It to your library. Figure 3 shows what our final
‘component would look like in a schematic. But
what if we needed to make changes and update
‘our design? We will cover that next.
Updating components
When you make changes to a component In a
library DesignSpark will only update the library
files and not the schematic and PCB files that use ft.
‘That's because every design file keeps its own copy
‘of the component so that changes in a component.
library can’t accidentally affect an existing design.
‘So how do we update those local component cop-
les with the new component library information?
‘One way Is to delete a component and then add
it back into the design but this is a dangerous‘operation that could have unintended side effects
like breaking net connectivity in your design. This
would be especially risky In a PCB file because
It could break the link to the schematic for that
file Instead you always want to go into the Tools
menu and select “Update Components” and then
‘choose which components you want to update.
This works in schematic and PCB files.
‘You will almost always want to either browse for
the components or choose to update the selected
‘components. You don’t usually want to update
all components automatically unless you review
all of the pending changes to make sure that
there won’t be any unexpected updates. Either
way you will get the Update Components win-
dow in Figure 4 if you update components in a
‘schematic. The PCB version of the Update Com-
ponents windows is very similar.
‘The “Only update item if version Is different in
library” option tells DesignSpark to only update
‘a component if It’s different from what’s in the
brary. The “Keep value positions” option tells
DesignSpark to try and leave all of visible com-
ponent fields in thelr current locations. This usu-
ally works but you will still want to double check
that nothing has moved on you after the update
because even though DesignSpark will keep the
‘same anchor point sometimes the text justifica-
tion will revert to what was used in the library.
Enabling the “Keep existing component values”
‘option will keep all of the component value fields
In your design, otherwise the values will be over-
written with the values in the library. This option
Is important when you modify a component's
value fields in the library and you want to trans-
fer those changes to your design. The Update
‘Components window adds another option called
“Remove pad style exceptions” when you update
‘@ PCB component. You would normally leave it
selected so that DesignSpark will clear all of the
errors it detected with the previous footprint.
Replacing and changing components
‘Sometimes you need to replace or change a com-
ponent as you work on a design. For example,
1 like to have a different resistor component for
each value In a design so that I can put all of the
manufacturer’s part numbers in the component
value fields and make a proper BOM later. That
means that I just change the component when,
I want to change a resistor’s value.
If you haven't already placed the component on
the PCB then it doesn’t matter if you Just delete
‘a component and then add a new one to replace
It. But if you do this and the part Is on the PCB,
DesignSpark will delete the component and then
add the new one to the component bin. A bet-
ter solution Is to replace a component without
deleting It first. You do this by selecting the com-
ponent and open its properties. Then you click
‘on the Change button which opens the Change
‘Component window where you can select the new
‘component. With this method DesignSpark will
leave the component on the PCB and you also
don’t have to worry about matching the refer-
ence designator.
Conclusion
Today we've taken a pretty close look at how to
create components with the DesignSpark wizards
‘and how to update designs with the library changes.
Next time we'll learn how to use multiple com-
ponent gates and hidden power pin connections.
ao3e7)
Figure 4.
Update Components
window.8y Neil Gruending
Web Linl
Tantalum Bead Capacitors
Weird Component # 10
What's the first thing you check when a plece of
electronics stops working? I bet it’s the power
supply voltages and if you are repalring a board
that over 20 years old then you've probably
your share of tantalum bead capacitor fallures.
If you're lucky they will ust short out and current
limit the power supply but I've also seen them
explode Into a small ball of flame! But whence
the fall. the noise. the vile smell?
Tantalum capacitors like the dipped ones in Fig-
ture 1 are a form of electrolytic capacitor that
uses oxidized tantalum powder pressed into a
pellet as its dielectric. The tantalum powder allows
capacitors to be bullt with a very high capaci-
tance for their size and since the powder Is solid
they also have a very wide temperature range.
But perhaps one of their best properties Is that
they have a very low equivalent series resistance
(ESR) compared to other electrolytic capacitors,
types like aluminum electrolytic.
The tantalum powder Is a dielectric because It
easily forms an insulating oxide layer as part of
the manufacturing process, The oxide layer thick-
ness Is controlled by applying a polarized voltage
to the capacitor called the formation voltage which
{s usually a multiple of the working voltage. The
capacitor will also get the same polarity as the
formation voltage. It's this oxide layer that is crit-
{cal to the tantalum capacttor's safe operation.
It's thelr high capacitance and low ESR that
‘makes tantalum capacitors a good choice in power
supplies and for a long time they have been used
as a drop In replacement for small aluminum
capacitors. But if you do that in a power supply
rcult you could have a pretty high failure rate
because it tums out that tantalum capacitors are
sensitive to voltage transients and ripple current.
‘Tantalum capacitors can absorb small voltage
transients within thelr operating range but if the
transients are too large then they can punch
through the thin oxide layer on the tantalum pow-
der and damage the capacitor. The capacitor’s
low ESR can unintentionally amplify the voltage
spikes (ringing) and can also cause damaging
current spikes. Once a capacitor is damaged it
will degrade until it eventually shorts out. If the
ower source Is large enough then the capacitor
‘can actually explode then burn the circuit board.
But tantalum capacitors can be used safely as long
{as you watch their voltage and current ratings.
Normally you can get away with using an alumi-
‘num capacitor near its maximum rating but for a
tantalum capacitor you need to derate its working
voltage rating by at least 50%. You also have to
‘make sure that the ripple current won't exceed
the capacitor ratings by adding enough capacitors
in parallel. The downside to paralleling capacitors,
Is that it also reduces the capacitor ESR, can cre-
ate a small tank circult with the inductance in the
PCB traces and create unexpected voltage spikes
in power supply applications.
Electronics roughly from the late 1980s through
‘mid-1990s used epoxy dipped and surface mount
tantalum capacitors quite a bit in their power
‘supplies and for decoupling. Unfortunately these
capacitors are now known to have a pretty high
fellure rate (Figure 2). In some cases It’s now
‘common advice to test or replace all the tantalum.
‘capacttors when repairing 1980/90’s electronics.
It’s hard to know exactly why the failures hap-
pened but according to Kemet [1] early tantalum.
capacitors weren't actually designed for power
supply applications and they required a signif-
cant amount of external resistance to operate
reliably (usually several ohms per volt applies to
the capacitor). It's also possible that many designs
from that era were using the capacttors near their
voltage ratings and that they simply just falled
because of many small transient events. For exam-
ple, it was common to see 6.3 V capacitors used
for 5 V power rails.
‘Tantalum capacitors are being used less often in
znew designs thanks to MLCC ceramic and better
‘aluminum electrolytic capacitors but if you need
a lot of capacttance in a small package tantalums
are hard to beat. Modern tantalums have dealt
with the problems mentioned here with surge-
tested and fused parts. You just have to make
sure that that they are used within their limits.
(140366)
[1] http://canada.newark.com/pdfs/techarticles/kemet/Tantalum-in-Power-Supply-Applications.pdftas gt
8x8x8 cube
* Every LED
individually
addressable
'* Optional use of
infinity mirror
‘= Animations can
be simulated
+ Developed and
programmed
using Flowcode 6
and ECIO40P16
© Arduino
patchable
Infinite RGB LED Cube
with Flowcode
by Ben Rowland,
‘The 8x8x8 LED cube project pub-
lished on the Instructables website
[1] was very detalled and yet looked
simple enough for me not just to complete
but add substantial enhancements as well.
After planning on creating a larger single color ver~
sion of the cube I quickly realized that to double
the display dimensions to 16x16x16 meant octu-
pling the number of LEDs and interconnections. The
thought of processing 2,048 LEDs was too much
for me so I scaled down my thinking and instead
decided to repeat the &X8x8 (512-LED) design but
Using full color RGB LEDs instead of single color
LEDs. Even at 8x8x8 RGB LEDs it stil tallles up to
‘around 2,200 solder joints so be warned!
From my research I also came across some great
infinity mirror projects which are basically LEDs
sandwiched between a mirror and a pane of glass
with a one-way mirrored surface to create an
effect that the LEDs go on forever (Figure 1). 1
decided to apply some of the simple techniques
to my cube to try and extend the display beyond
the bounds of the actual LEDs.
With 512 RGB LEDS in the design each with their
‘own three internal LEDs a lot of control signals
are required to switch the LEDs on and off. There-
fore a method is needed to share control signals
An Instructables project
colorized & enhanced
Matrix Technology Solutions Ltd. (UK)
Here's how to take a plain single-color 8x8x8 LED cube
project to the Next Level. The newly released Flowcode 6
software development suite was instrumental in a lively
journey into understanding and achieving the simulation
of animations on ‘full color’ LED cube that’s capable of
mesmerizing visualizations.
between LEDs (multiplexing). In the design the
LEDs are cathode-grounded with a current lim-
Iter resistor on the anode.
Multiplexing tool 1: buffer ICs
‘The LED cube employs two types of multiplex-
ing to allow all 512 RGB LEDs to be driven inde-
pendently. The first method uses octal flip flop
buffer ICs to allow us to create enough control
signals to drive a full 8x8 segment, I.e. 1/8" of
the cube. In an 8x8 section there are 64 LEDs
which means we need 192 control signals to allow
us to drive all the individual color channels. To
drive all the signals we need to chain 24 of the
buffer ICs together so that the output of the first
buffer drives the input of the second buffer, the
second drives the third and so on.
igure 2 shows a simple schematic with two
buffers chained together and connected to drive
LEDs. The dock signal Is driven by the controller
‘and used to shift the output signals from one buf-
fer IC to be passed to the next buffer IC.
I made the buffer driver fairly modular to allow
‘me to scale up or down the size of the cube
depending on how many LEDs I wanted. To do
this I created a PCB with three buffer ICs on
allowing me to control a single row of eight RGB‘One method of achieving
LED mattiplecing isto
“insert” the devices between
‘two buffer ICs to which
intelligent control is applied
Figure 2.
implementation ofthe 8x8x8
RGB Color LED Cube.
ish) buffer board. Eight of
these are required for a full
Figure 3.
‘Schematic of the modular(-
3993943
Sseossae
18S
oa
PEEEEEEe
Ssasssss
2@28 5 a
a) a}3} 3) 3) 3) 3)3)
roe
BevesaeeFigure 4.
‘One of eight NPN transistors
used to switch 8x8 sections
‘on and off under software
‘control, completing the
‘overall multiplexing scheme
for 512 RGB LEDs.
Figure 5.
‘The stack of driver boards.
LEDs. With eight of these driver PCBs chained
together it allows me to control the entire 8x8
‘segment of the display. The smaller 16-way rib-
bon cable is used to pass the 10 control signals
plus power and ground between the PCBs. The
wider ribbon cable is used to pass the signals
‘onto the LEDs via the on-board resistors. Each
board Is fitted with Its own capacitors to allow a
bit of current to be sourced locally as and when
needed by the LEDs.
Multiplexing tool 2: NPN transistors
In Figure 3 each of the 8x8 LEDs in a single
segment is driven via our chain of buffer ICs.
To allow us to control the other seven 8x8 seg-
ments of the display we need a second method
‘of multiplexing. To do this we take the cathode
pins of all the LEDs within the 8x8 segment and
‘connect them all together. We then connect these
to ground via an NPN transistor which allows us
to enable and disable all the LEDs in the 8x8
‘segment at once using a single control signal to
the transistor’s base pin. Figure 4 shows the
approach schematically; Figure § the resulting
stack of eight driver boards.
By connecting all the LED cathodes together for
each horizontal 8x8 section we can then use
‘eight NPN transistors to enable or disable each
of the &xs sections and therefore control each
of the LEDs in each section individually. This is,
great but obviously this means that we can only
light up 1/8 of the display at any one time. By
‘constantly switching which 8x section is active
at fairly high speed we can build up the entire
display so it appears to the human eye that the
entire cube Is lit and constant.
The Build
‘So that’s pretty much it for the theory, It’s time
to pull up our socks, make a brew and dive into
the world of bending wire and soldering. There are
two fairly laborious tasks that are required when
building a LED cube, the first being bending LEDs
and the second being soldering the bent LEDs
together. Each step required a Jig to make the
process more manageable and to help maintain
quality while I slowly lost the will to live. Luckily
I managed to do most of this stage during the
Christmas vacation so there was enough going
on to keep my mind interested while my hands.
were occupied on the task.
Bending LEDs
‘The first step for assembly was to take all 512
LEDs and bend them correctly. To do this 1 drilled
‘a Smm hole in a spare piece of wood and checked
that a LED fit snugly and flush to the wood but
could also be inserted and removed easily. Once
Thad my hole correct I drew some guide lines to
help with the bending. As pictured in Figure 6,
the lines I drew were one vertical running through
the center of the hole (A), one horizontal line run-
ring through the center of the hole (B) and one
horizontal line running through the very edge of
the hole (C). A metal ruler came in very handy
during the bend stage.
‘The photos in Figure 7 show the steps to follow
when bending the legs.
1. Insert the LED into the jig ensuring you have
‘got the LED in the correct orlentation. The pins
should all be sat in line with the horizontal
line (B) and the cathode pin should be the
second pin from the right.
2. First Bend: bend the cathode pin downwards
‘and the anode pins upwards parallel with the
line (A). Ensure they are fairly flat to the board
‘and the bottom of the LED.
3. Second Bend: using the metal ruler bend the
cathode pin to the left so it Is parallel with
line (8).
4. Third Bend: using the metal ruler on the sec-
‘ond horizontal tine (C), bend the anode pins
‘upwards again. One LED down, 511 left to bend!
Assembling 8x8 sections
‘Once you have at least 64 bent LEDs you are ready
for the next stage which is to assemble one 8x8
section of LEDs. To hold the LEDs in place I cre-
ated a jig using my trusty 3D printer and a design
T uploaded to Thingiverse (2). If you don’t have
‘access to a printer then the Instructables guide [1]
describes a different method to hold the LEDs inplace. The LEDs were soldered together by inserting
‘each LED one at a time into the jig before soldering
the anodes together on the current column and the
‘cathodes together on the current row as shown in
Figure 8. Take your time and ensure that every
solder joint you make Is nice and strong, spending
‘a bit more time here will potentially save a huge
‘amount of time later on when it comes to getting
the thing up and running.
‘As each complete panel was finished I made sure
to give it a full test while it was stil in the Jig
to ensure that every LED lit correctly and that
there were no breaks or shorts in the panel. To
do this I connected long lengths of wire to my
5-V power supply. At the end of one of the pieces
of wire I soldered the larger of my two resistor
values used on the driver board from Port 1 and
this allowed me to drive all of the LEDs without
‘any risk of damage. Using my trusty metal ruler
pressed against the unconnected common leads
Twas able to temporarily short all the common
pins together to ground meaning I only have to
test each anode column once rather than having
to test each and every LED individually. To get the
panel of LEDs out of the jig I just gently pushed
‘on the top of each top LED in turn and repeated
Until the entire panel popped loose. Setting the
completed panel aside I went back to bending
LEDS for the next &x8 panel.
Combining the 8x8 sections
Afterall the LED legs were bent and all the LEDs
‘were assembled into panels it was time to start
Joining the panels together. I laid the first panel
flat on a desk and soldered two lengths of straight
‘single core wire to each the cathode wires one at
elther side of the panel to provide a good level
of support and a bit of redundancy Just in case
‘one of the solder connections on one of the wires
were to fall. To obtain the straight wire I used
the technique of holding both ends with a pair of
pliers and pulling hard. I had to experiment with
a few different types of wire before I found one
that would be happy with the current from 64 x.
3 LEDs and would also straighten nicely without
too much effort on my part. I used a few small
match boxes to space the next panel away from
the first. Taking my time to ensure everything
was as lined up as possible I repeated this pro-
cess until all of the panels were together and
then gave the LEDs another full test to ensure I
hadn't missed anything. A virtual 3D view of the
‘cube in the making like in Figure 9 shows the
Position of the 8x8 section.
Preparing the base
The cube once fully assembled Is fairly strong
but all it would take would be a bit of weight
applied in a wrong place and all that work would
be ruined. I used the same piece of MDF board
that I used to create my jigs and drilled 5-mm_
holes into this at the correct pitch for the legs of
Figure 6.
Guide ines (iter) to help
with the LED pin bending.
Vas
Figure 7.
Method of bending the LED
pins for easy assembly into
a cube shape.
Figure 8.
‘jig is used to hald the 88
LED arrays together for the
purpose of soldering the
‘anodes and cathodes thus
creating rows and columns.Figure 9,
AD rendering showing
the whereabouts of an 8:8
section within the cube.
Figure 10.
‘The program for the RGB
LED cube was developed
using Flowcade 6 shown
In action here. Note the
‘simulation in the right hand
ppane. The full program
‘and more is contained in
archive fle 140149-W.zip
downloadable at [3].
the bottom row of LEDs to go through the MDF.
‘To work out the pitch I took measurements from
‘outer left LED to outer right LED on both sides
of the cube and then averaged the spacing, then
repeated for front to back. I then drilled a further
‘eight 3mm holes along one edge for the cath-
‘ode wires to come through to the cube. Finally 1
routed 2 6-mm groove for my glass cover to fit
Into and spray painted the MDF.
Details on inserting the cube onto the base, add-
ing the common-cathode rails and the project.
wiring may be found in a supplementary doc-
ument available for free downloading from the
Elektor magazine website [3].
The Brain
T used some pieces of veroboard to allow me
to connect an ECIO40P16 ‘brick’ directly to my
5-V power supply and to create the NPN com
‘mon driver circutry. A S-V power supply must be
used to allow a fairly large current to flow without
‘generating any additional heat. The Flowcode LED
Cube component is flexible so will work with pretty
‘much any microcontroller family apart from 8-bit
PICs as these cannot have arrays greater than
256 bytes in size. The ECIO40P16 packs a lot of,
punch for its size but with sultable code patching
a standard AVR based Arduino should also be able
to drive the cube if that’s what you have available.
Whatever method you choose of packaging or
securing the control electronics to the cube
assembly, remember to add a hole to allow your
power supply to be connected. Some of the pop-
ular SMPSUs come in small metal cases so this
could also be Included inside the box to neaten
things up a bit. You may also want to leave the
USB cable connected to the ECIO to allow you
to a) reprogram without having to re-open the
casing and b) for communications via USB should
you want to go down this route using the Flow-
code USB components.
Enter Flowcode 6
‘To create the simulation and the code to drive the
display I used the Flowcode v6 software and this
had everything I needed to allow me to create
‘a masterpiece. I began by creating a sphere on
the panel, making it invisible and then cloning
the sphere enough times to match the x, Y and Z
dimension properties. I then went about creating
routines allowing me to get and set the color of,
each individual sphere. This then allowed me to
generate the line and cuboid drawing routines as
well as the slightly more complex shift and rota~
tion macros. By using a previous graphical LCD
component I was able to rip out the text drawing
‘macro and by finally adding a double buffering
system the simulation side of the component was
about feature complete.
To add the embedded functionality I created an
array of 16-bit variables to store each of the LED
color values in the cube. I then created a rou-
tine which could be called repeatedly to handle
things like clocking out the data to the buffers
‘and switching between the eight common chan-
nels. Finally all that was left to do was to add
code into the get and set color macros to allow
the array to be read and written when not run-
ning via the simulation. The final component is
‘now available [3] which can simply be draggedonto the Flowcode panel. The Flowcode sketch
Ing ‘sheet’ Is shown in Figure 10.
Visualizations
The Flowcode tool has been used to develop a set
of test programs to generate a rain effect with
lightning, a fireball, two interacting plasma balls,
a textual display and a vector based animation.
A video Is available on YouTube [4] showing the
visualizations running on the hardware. The next
Item Description
RGB LED, Smm, diffused lens, common cathode
5V SA switch mode DC power supply
Microcontroller Brain (ECIO40P16 or Arduino)
SN74ACS74N octal flip flop
16-Way IDC ribbon Cable
24-Way IDC ribbon cable
1L0uF aluminum electrolytic capacitor
100nF ceramic disk capacitor
1009 0.25W resistor (green/biue LEDs)
1800 0.25W Resistor (red LEDs)
16-way IDC socket
16-way DIL header
24-way IDC socket
24-way DIL header
T1P122 NPN SA transistor
‘Small piece of Veroboard
Tempered glass shelving émm / 0.25" thick
Sheet of fiberboard / MDF 20mm/ 0.8" thick
Spray paint to color MDF
Reflective car window tint
step Is to add a microphone to the internal cir-
cultry and use this to control the movement of
the visualizations using techniques such as FFT
to chop up the audio signal into frequency bins.
Plenty of challenges there—let us know how you
get on.
(140149)
Quantity _| Source Part Number
512 | eBay
1 eBay
1 Elektor Store
24 Farnell 165-2006,
2m/7t_| Farell 120-7442
‘4m/13ft_| Farnell 120-7439
8 Farnell 211-2751
8 Famell 187-1077
128 | Farell 933-9043
64 Farnell 933-9230
16 Farnell 221-5235,
16 Farnell 102-2240
8 Farnell 221-5253,
8 Farnell 159-3448
8 Farnell 980-4021
1 Farnell 120-1473,
si B&Q/ Lowe / Home
Depot / DIY Store
A B8Q/ Lowe / Home
Depot / DIY Store
a B8&Q/ Lowe / Home
Depot / DIY Store
1 Halfords / Auto Partsfaeries
Distance
and Level Gauge
With Alarm Function
Do you need to know how full your oll tank or
water tank is, without requiring vast compu-
tational effort or expert knowledge? You fill a
large barrel with water from the garden hose
‘+ Measures the level status of liquids
'* Watchdog function monitors fill level, with relay output and alarm LED
‘+ Programming of min./max. alarm levels infinitely variable
‘+ Stores min./max. calibration values for up to ten tanks or containers
in memory
‘= Also measures distance
+ Intuitive menu guidance using LCD display
By Jérg Trautmann (Germany)
‘Small, widely available
and dirt-cheap ultrason-
ic sensors enable us to
design both simple and
lavish measuring devices
for all kinds of ranging.
Take one of these modules, add a display, a couple of pressbut-
tons and a microcontroller loaded with software, and you now
have all the ingredients for a circuit of this kind.
and would like to cut off the water flow using a
‘magnetic valve when it has reached the desired
level? Or maybe you would just like to measure
the distance between two objects? The possibil-
ities using the level and range meter described
here are virtually limitless!
The extent to which cylindrical or cubold contain
ers are full can be determined either mechanically
with a float and potentiometer, or else capaci-
tively with ultrasonics or a laser device. Both
approaches, mechanical and capacitive, require
‘auxiliary components such as floats and sensors.
If accuracy of measurement Is your prime con-
sideration a laser Is definitely the best solution,
yet even this method has its pitfalls. For exam-ple, fog and steam can cause reflections for the
laser, falsifying the result.
Since influences of this kind affect ultrasonics
hardly at all, I settled on ultrasonic sensors for
this cost-effective device. A further advantage of
this solution is that it requires no physical contact
to be made with the liquid medium. Into the bar-
gain we also obtain a tool for measuring distance.
‘The frequency of 40 kHz normally used by ultra-
sonic transducers corresponds, at an ambient tem-
perature of 20 °C, to a wavelength of 8.5 mm.
‘Sound waves in this frequency spectrum do not
disperse to any great extent and diverge (in a dlub-
shaped form) with an aperture angle of around
15°, Perfect qualifications for our purpose then,
since the side walls of the container will have
effectively no influence on the reflected signal.
The ultrasonic sensor used here was already
described exhaustively in Elektor a few months
ago in the 2014 Project Generator issue [1].
‘Accordingly we will Keep the functional descrip-
tion short and to the point. A trigger pulse causes
the ultrasonic module to transmit a burst signal.
This signal is reflected by the object to be mea-
sured, say the water surface in a rainwater bar-
rel, and received back by the ultrasonic module
as an echo signal. Since the sound traverses the
distance to the reflecting object twice during the
echo period, we can state that:
distance =
0.5 x velocity of sound [m/s] x echo period [5]
Circuit and components
‘The schematic in Figure 1 Is based on three
components, the well-loved ATmega8 microcon-
troller, a LCD connected to this plus the ultra-
sonic module. As well as the HC-SR04 module
(Figure 2) you can also use the almost identical
= Ue
5
Figure 1.
Simplified circuit of the
Distance and Level Gauge.Figure 2.
‘The compact ultrasonic
‘module HC-SRO4.
Figure 3.
Procedural diagram forthe
US-020. Both modules are in the $5 / £3 price
lass, making them unbeatably attractive for use
in a do-tt-yourself measurement device.
Ascertaining the manufacturers of these modules
Is not an easy task but they are widely available
in electronics stores, particularly those that spe-
lize in robotics. When you check out the data
sheets, however, you will discover wide varia-
tlons. One time the detection distance for the
‘two models will be shown as 2 cm-3 m (.8 inch
= 10 feet), another time as 3 cm - 7 m (1.2 inch
= 23 feet). Further investigation will uncover
other divergent detalls, even for one and the
self-same model. Hence the current consumption
will vary between 3 mA and 15 mA depending
‘on which data sheet you read. Reliable data can
bbe determined only by doing your own research.
Generally suppliers of these modules agree on
the following data:
‘* Operating voltage: 5 V DC
‘* Temperature range: 0-70 °C
‘© Diffusion angle: 15°
‘© Operating frequency: 40 kHz
‘Trigger input signal: 10 ps
‘The minimum distance between transmitter and
receiver capsules for the HC-SR04 module is so
‘small that measurements can be made in can-
Isters (the ultrasonic module needs to be dis-
charged when dealing with highly inflammable
fluids, owing to risk of explosion!). If you are tak-
ing measurements in containers with particularly
small aperture diameters you can resort to the
‘SRFO2 ([4] ultrasonic module, which although not.
pin-compatible, is nevertheless equipped with a
serial/I°C interface and uses a single capsule for
both transmitting and recelving. As the transmity
receive angle Is very acute, with this model you
need to bear in mind that the minimum distance
from the medium being measured amounts to
16cm.
To simplify the menu guidance a four-line,
16-character LCD display is employed. Potenti-
‘ometer P1 adjusts the contrast. R3 is the series
resistor for backillumination and should amount
to around
R3 = (5- Vi) / Trem [2].For this you need to consult the data sheet of
the display. With many LCDs the series resistor
Is already provided internally and in that case
you can replace R3 with a wire bridge or strap.
To save energy you might also consider a setup
involving a switch.
‘The changeover relay RE1, whose contacts are
connected to K3, are controlled by port pin PD7
and driver transistor T1, and the alarm LED
(low-current) by port pin PDS. A low-dropout
voltage regulator LM2940CT-S ensures a stable
5 V supply voltage from four 1.5 V batteries, This,
somewhat exotic voltage regulator delivers up
to 1A and can therefore be loaded much more
heavily than the usual 78LO5 with its 100 mA.
‘Naturally you can also use a plug-in (‘wall wart’)
AC power supply (<26 VDC) for this project, con-
nected to K1. With the relay energized and the
LCD illuminated the circuit draws around 150 mA.
To achieve maximum accuracy of measurement,
the microcontroller needs an external 16 MHz
crystal. A couple of passive components com-
plete the circuitry.
The software
The program in the microcontroller must cover
the following functions:
‘ Indication of the level of liquids
‘© Watchdog monitoring of this level with relay
output and LED alert
‘Infinitely variable programming of the mir/
max alarm level
«Storage of min/max calibration values for up
to ten containers or tanks
« Distance measurement
«Intuitive menu guidance using LCD readout
* Offset correction for distance measurement
‘* Manual divisor correction to accommodate
low and high temperature extremes
The software follows the procedure shown in Fig-
ture 3. In view of the limited amount of memory
space In the ATmega8, readout messages are
given in English only. Operation makes use of the
four pressbuttons Return, Next, Plus and Minus.
Because of the complexity of the program cod-
ing, which can be downloaded along with the hex
file and the PCB layout at [2], it has been subdi-
vided into meaningful procedures and provided
with corresponding commentaries, so that even
beginners should find their way through it rapidly.
Ponca maul cuts
eRe memer tl
‘The velocity of sound cy in air amounts to 331.5 m/s measured at a
‘temperature of T = 0°C. The velocity of sound is not dependent on
‘atmospheric pressure but purely on the air temperature 0 in degrees
Celsius:
=o: Via)
where « is the coefficient of expansion of 1/273.15 = 3.661x10-? 1/9C.
From this arises the approximation:
9 = 20.063-V0+273.15 m/s
We can see that for precision measurement the influence of
‘temperature is by no means insignificant. Here are some examples of
sound propagation times at 0 °C and 20 °C.
nce incm Time elapsed in ms at 20°C Time elapsed in ms at 0°C
2 0.117
0.121
10 0.583
0.603
50. 2.915
3.017
100) 5.831
6.033
200 11.662
12.066
300 17.492
18.100
‘The actual measurement process follows. To bring
the ultrasonic module connected to K2 into trans
mittting a signal, a pulse 10 pis long with a fall-
Ing edge Is sent via port pin PD2 to the trigger
Input. As a result, about 250 uss afterwards, the
ultrasonic module transmits a burst signal with a
frequency of 40 kHz and duration of 200 ys. The
echo output, which is connected to the micro-
controller via port pin PD3, switches now to High
level and the ultrasonic module stands by to
receive the reflected signal. If this occurs, the
echo output fips back to Low. Timert Is ticking
away throughout this process, so that after the
timer Is halted, the distance can be calculated.
After 50 ms if no echo signal arrives, measure
‘ment for the current cycle Is cancelled. To achieve
the best possible results the mensuration cycle
Involves 16 separate measurements. The program
code for this can be examined in the procedure
Gauge_distance().
Now a word of advice for people doing their own
“burning’ and taking advantage of the program-
ming interface for the controller at K4, BecauseFigure 4
Upper and lower sides of
the PCB.
Component List
iow current, re,
cs47C
uM29407-4.0
Miscellaneous
K1 = DC-power socket, 1.95mm pin
(Farnell 1217037)
der
the program is extremely wide-ranging, the
8 K-capacity flash memory Is 100 % full. For
this reason the demo version of BASCOM-AVR
cannot be used for compiling, since it allows only
4K (Le. 50%) of memory usage. While burn-
ing you can rapidly blunder into a trap: in this
circult the ATmega8 operates with an external
16 MHz crystal, making It necessary to set two
fuses. CKOPT should be activated to assure reliable
operation of the oscillator. This method increases
current consumption somewhat but you do obtain
stable oscillation in return. It’s essential to set
SUT_CKSEL to Ext. Crystal/Resonator High
Freq.: Start-up time: 1K CK + 64 ms! The
list of options provides a wide selection of set-
tings. If you make a mistake here, under some
cdrcumstances you can ‘brick’ your ATmega8 once
programmed, as it may well be unable to find
its feet again afterwards. Better then to double
check precisely which settings you have selected,
A screendump of AVR Studio showing the correct
fuse settings is included in the download package.
Construction and commissioning
Construction Is extremely simple thanks to the
very manageable number of components. You can
buy the double-sided printed circutt board (Fig-
ure 4) from Elektor or etch it yourself at home.
The relevant files are In the download package
[2]. Some handiwork and skill are necessary to
create cutouts in the case for the LCD readout,
the ultrasonic capsules, the pressbuttons and the
switch, How you arrange the ultrasonic capsules
is a matter of personal taste. Installing the ultra-
om seteae or)
Perrot
resonic modules separately on a moderately long
screened cable Is also concelvable, in case reading
needs to take place in another room.
Once the programmed ATmega8 has been
inserted and the ultrasonic modules connected,
you can switch on the device for the first time.
At very least the background lighting for the LCD
should illuminate. If this is not the case, dis-
connect the power supply and double-check the
component placing! During the start phase Dis-
tance & Level Gauge 2.4 (Figure 5) should be
visible on the display for two seconds.
‘Now you can perform the basic settings. To do this
you switch off the device, then turn it on again
while holding down the Return button. Having
released the button, you will be asked the width
of the container being measured. At this point
you can press the Plus and Minus buttons In
order to enter an offset in 5 mm increments for
taking into account the distance from the top of
the ultrasonic module to the leading edge of the
container. This gives you
a simple way, for exam-
ple, of measuring the dis-
tance from one wall to the
other later on. The best
method for this is to take
a2 m reference measure-
ment with a two-meter
wooden rule (or measure
three feet using a carpenter's yardstick). The
value Is confirmed using Return.
Following this you are asked for the divisor value
used for correcting the value measured. This Is
necessary since the velocity of sound Is tem-
perature-dependent. In the temperature range
from -20°C to +40°C the velocity of sound varies
from 312.85 m/s up to 349.32 m/s. The devia-
tion is virtually linear, so that for a temperature
variation of 10°C you can expect an inaccuracy
of about 2%. Panel 1 contains some formulae
and a table of values for the elapsed times to
The latest on electronics and
information technology
¢ Videos, hints, tips, offers and more
Exclusive bi-weekly project for
GREEN and GOLD members only
Elektor behind the scenes
In your email inbox each Friday
@ektor
Sean bee ems te Wo net
Register today at www.elektor.com/newsletter,
(DeteeTV goes naebe expected. Incidentally,
atmospheric pressure has
no influence on the veloc~
ity of sound.
‘Anyone prepared to accept
up to 5% inaccuracy in
this connection need do
nothing at all. On the
other hand, if you wish
to take measurements in
temperatures below 15 °C
or above 25 °C and with
a higher level of accuracy,
a division factor must be
introduced. The higher the
temperature, the greater
the divisor must be. The
values for the width of the
container and the divisor
must also be retained
after a battery change and
can be entered afresh at
any time,
The Select mode: menu
should now be visible.
Pressing the Return but-
ton will take you to the
tank selection menu, The
opportunity is provided
to carry out calibration
functions for up to ten
different tanks or other
containers. The only con-
dition made is that the
container shape must be
as close as possible to a
cuboid or cylindrical form,
otherwise linear measure-
ment Is impossible. Hav-
ing selected your tank
number you land back
at the main menu. After
pressing the Next but-
ton the menu option CaF
Ibrate tank appears. Hit-
ting Return now goes to the calibration menu.
Having selected empty-level calibration, you are
asked if you are ready to perform the calibration.
You don’t necessarily need to empty the vessel in
question for this purpose; instead you can simply
measure outside the tank the height from the
filler neck down to the ground.
Once the empty level has been calibrated, you
reach the menu for full-level calibration (Fig-
ure 6). The default value is set as a minimum
of 3 cm, which you can accept by pressing Next.
If, however, you wish to perform a calibration for
the full-level, put the device in position above the
filled container and press Return.
After returning to the main menu you can perform
the first level measurement. To do this, select
menu option Gauge level and confirm with Return.
Measurement begins now and the result is dis-
played. Next carries out a fresh measurement,
Return leads back to the main menu.
To test out level monitoring you should select
the Level Watchdog menu. In the menu that fol-
lows (Figure 7) the alarm type can be selected:
Full will activate the alarm when the permitted
fil quantity is exceeded and Empty when it falls
short. Having chosen your alarm type, you can
alter the threshold value in the Level Alarm
menu (Figure 8). For the default values we have
defined the maximum level as 95 % and the min-
imum level as 5%, but these can be varied using
the Plus and Minus buttons. All the calibration
values made are stored in the EEPROM and are
retained there even after a change of battery.
The first measurement follows next and the cur-
rent level Is displayed (Figure 9). Measurements
are now taken every five seconds. If these fall
below the minimum value or exceed the max-
Imum value set, the display shows > Level
alarm <, the red LED illuminates and the relay
operates, for example to switch on a pump. If
the level status returns into the permitted range
after 5 s, the alarm function is cancelled. The 5s
measurement cycle avoids the need for a hyster-
esis function to eliminate relay contact bounce.
To exit from this mode back to the main menu,
ress the Return button (for up to 5 s). You can
now select the Gauge dlstanae menu. Each press on
the Next button initiates a distance measurement
(Figure 10). As before, you can exit from this mode
and go back to the main menu by pressing Return
(140208)By J.T. van Es
(Netherlands)
Figure 1.
Basic circuit.
Figure 2.
Output signal (10 Hz)
without positive feedback.
Figure 3.
Positive feedback via R4RS.
Figure 4.
‘Output signal (10 Hz) with
positive feedback.
Improved
Current Transformer
This report is a response to the two publications by Martin Ossmann in the April
and May 2014 editions about the dimensioning and use of current transformers.
Martin aims to reduce the lower cut-off frequency, determined by L/R, by looking
at the core material, among other things. While the method is not incorrect, simi-
lar results can be achieved much easier as shown in the report below.
Tr
i
f
ay Son 8g
Figure 1 shows the signal path of a current meter
built in 2005 and which was appropriate for its
purpose. It ended up in a closet after that, but
‘was retrieved again for this occasion. The current
transformer Is a pick-up coil from a ‘Tubantor’
fuel-infection system from 1983. This contains a
ferrite core with 80 turns. The -3 dB bandwidth
of this assembly is 7 Hz to 5.5 MHz. Using it with
2 10-Hz square wave Is therefore not such a
success, as Figure 2 shows. R3 has been added
to correct the offset of the amplifier.
By giving the amplifier a little bit of positive
feedback, using R4 and RS (see Figure 3),
the input resistance of the amplifier becomes
negative (adjustable with RS) and this effectively
compensates for Roy. When the circuit resistancereduces, L/R increases, Figure 4 shows this effect.
It even works well down to 1 Hz, if the positive
feedback Is increased a litle more, see Figure 5.
However, the DC stability leaves much to be
desired. Figure 6 shows a solution for this, using
‘a control circuit comprising an additional opamp,
R7 and C1. The opamp needs to be a type with
FET inputs so that It becomes possible to work
with large values for R7 and C1. C1 needs to
be a film capacitor in order to keep the leakage
‘current low.
Because the secondary winding is almost perfectly
short-circuited using this technique, there can
be no voltage drop across it any more—and not
‘across the primary either, apart from its own
‘copper resistance. The flux in the core, which
is already low in a current transformer, also
‘approaches the absolute minimum. The value
for L can be much lower in this case, which Is
beneficial for its HF behavior. The measurement of
DC signals is, however, not possible, this requires
‘Hall effect sensor. The annoying feature of such
a device Is that It requires a gap in the core,
‘which results in a much reduced mu and therefore
value of L.
Figure 5.
Output signal (1 Hz) with
‘more positive feedback.
In the past (1985, I think) we designed a beam
‘monitor using a Vitrovac ring core with an inside
diameter big enough to pass a beer bottle
through. The bandwidth we obtained then was
23 mHz to 20 MHz!
Figure 6.
Improved DCstability with
‘an additional opamp and
RICA.
(140266)
‘The author's amplifier setup,Safe High Voltage Power Transistor Measuring with Oscilloscopes
‘Sacig's CLIPPER CLP1S00V15AL is a high technology oscilloscope adapter that allows small voltages to be measured in the presence of very
high voltages, such as those present on switching MOSFETs or IGBTs (Insulated Gate Bipolar Transistors). Making accurate measurements in
the presence of very high voltages has previously been extremely challenging, but using the CLIP-
PER CLPISO0V1SAL, the Vizou or Rycu Of @ Switching transistor can now be easily seen in high
resolution e.g. 100 mV/div) on an ordinary digital esciloscope. Determining the switching
speeds, Safe Operating Area (SOA), and temperature effects of MOSFETs and IGBTs
now greatly simplified with the CLIPPER CLPISOOV1SAL.
‘The CLIPPER CLP1SOQVISA1 represents 2 leap forward in transistor switch testing,
‘essential both in the design verification phase and production process monitoring. In
typical use, the CLIPPER is connected between Drain and Source terminals of a Power MOSFET.
‘The output signal provides a 1-to-1 picture of what is occurring across the MOSFET, without the