0% found this document useful (0 votes)
151 views233 pages

Arduino Compilation

Arduino

Uploaded by

MaxiNaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
151 views233 pages

Arduino Compilation

Arduino

Uploaded by

MaxiNaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 233

BEST-OF SERIES

ARDUINO COMPILATION
ALL ARTICLES FROM ELEKTOR ● 233 PAGES

SELECT LEARN DESIGN SHARE

N ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
ARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
EARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
GN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
HARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●

Personal Download for Petar Crnojevic | copyright Elektor


Table of Contents
Page Article title Edition Pages
3 Arduino Software Development with Atmel Studio 12/2014 4
7 C Modules 11/2014 11
18 Extremely Low Frequency (ELF) Receiver 10/2014 8
26 16 Bit Data Logger 9/2014 6
32 Arduino is a Tool 7/2014 1
33 My first Shield :-) 7/2014 5
38 Lathe Tachometer 6/2014 4
42 3D Pad: Touchles Gesture Control Interface 5/2014 10
52 Microcontroller Bootcamp (1) 4/2014 7
59 Microcontroller Bootcamp (2) 4/2014 8
67 Microcontroller Bootcamp (3) 4/2014 10
77 Microcontroller Bootcamp (4) 4/2014 8
85 Microcontroller Bootcamp (5) 4/2014 10
95 Microcontroller Bootcamp (6) 4/2014 10
105 Microcontroller Bootcamp (7) 4/2014 12
117 Intel Galileo-Arduino 3/2014 2
119 Arduino Yún 1/2014 5
124 Numitron Clock and Thermometer 10/2013 5
129 Spot the Difference 7/2013 2
131 Off to the EF Library 6/2013 2
133 Motion-Detector Camera Trigger using Arduino 4/2014 5
138 Arduino AC Grid Analyser 12/2012 8
146 Thou Shalt Communicate 10/2012 6
152 Laser Projection with Arduino 7/2012 2
154 AVR multitool 7/2012 4
158 Arduino on course (1a) 7/2012 5
163 Arduino on course (1b) 7/2012 5
168 Arduino on course (2) 7/2012 5
173 Arduino on course (3a) 7/25/2012 6
179 Arduino on course (3b) 7/24/2012 6
185 Arduino on course (4) 7/23/2012 7
192 Arduino on course (5) 7/22/2012 6
198 Arduino on course (7) 7/21/2012 5
203 Android Switch Interface 3/1/2012 6
209 Arduino Shields 7/1/2011 1
210 Arduino Nano Robot Controller 7/1/2011 1
211 Support Board for Arduino Nano 1/1/2011 1
212 Wireless Instrumentation Network 11/1/2010 5
217 A voltage booster using Arduino 4/1/2010 1
218 Arduino + Theremin = Theremino 11/1/2009 4
222 Touch LEDs for Arduino 10/1/2009 6
228 Microcontrollers for Dummies 2/1/2009 5

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Arduino Software
Development
with Atmel Studio
By Wolfram Pioch
(Germany)
Debugging applications on the Arduino Due

If you normally use Atmel Studio to develop


software for microcontrollers in the AT(X)mega
family and are familiar with the advantages of work-
ing with a debugger, you will sorely miss the convenience
of these tools when you switch to the Arduino IDE to develop
sketches for the Arduino Due board. This article describes a suitable remedy.

Although it’s nice that you can get useful results


quickly with the many ready-to-run Arduino sam-
Figure 1. ple sketches already available, when you start
The actual Arduino version, developing serious software for an Arduino board
board and programming
with an ARM processor you are confronted with
interface are selected on the
the following significant shortcomings:
toolbar.

• Compiling the program in the Arduino IDE


takes too long.
• Loading the program takes too long.
• No genuine hardware debugger is available.

To remedy this situation, the author has devised


a suitable alternative.
One reason for switching to a 32-bit microcon-
Figure 2. troller is faster access to the hardware, especially
The location of the Arduino the I/O pins. Accordingly, a good way to test the
IDE folder can be entered in processing power of a microcontroller is to write
the configuration window. a sample program (Arduino sketch) that gener-

3
46 | December 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Arduino & Atmel Studio

ates a pulse waveform with the shortest possible


pulse width and measure the pulse width of the
output signal. In this article we describe how you
can program a test sketch for this purpose using
Atmel Studio 6.2 [1].

Arduino compatibility
The procedure described here assumes you have
Atmel Studio 6.2 (or later) installed under Win-
dows. To make the Atmel IDE compatible with
Figure 3.
Arduino, you also have to install a free add-in
The Micro Explorer window
called Visual Micro [2], which is an Arduino IDE
of Visual Micro.
for Microsoft’s Visual Studio and Atmel Studio.
Visual Micro is directly available in Atmel Studio tion Explorer window in Atmel Studio. There the
after it has been installed. Arduino references are shown as links on the
Reference tab. A click on one of the entries takes
The USB-based Arduino debugger available from you to the corresponding website in the config-
[2], which is not free, is not necessary because ured browser. The Examples tab holds a list of
debugging with the Atmel ICE is significantly more examples (including library examples) from the
convenient. The latter tool is available in vari- Arduino IDE, grouped by topic.
ous webstores at prices in the 100 dollar range
(see the review in the October 2014 issue of Sketches in Atmel Studio
Elektor [3]). The expenditure is worthwhile if A major benefit of the Atmel Studio IDE is the
you use Atmel microcontrollers more than just code completion function, which you now have
occasionally. available for Arduino sketches as well. For this
With this debugger you can set real breakpoints you have to enable Visual Assist X via VAssistX
without recompiling the program, observe vari- Ž Enable/Disable. With this enabled, all possi-
ables in the Watch window, and examine or ble completion options are listed each time you
Figure 4.
change memory contents. What’s more, you can type a character in the Code window. For exam-
The Atmel Studio editor
inspect the numerous I/O registers and alter them ple, if you type “S” at the start of a new line in
helps you avoid typos
with a mouse click. a sketch, the terms Serial, Server, SPI and so on
by suggesting function
After you install Visual Micro, a new toolbar are suggested. You can then select the appro- names and options for
appears in Atmel Studio. On this toolbar you priate term directly, with no risk of typos. Even autocompletion.
can select the current Arduino version (1.5.x), better, after you type a dot, for example after the
the board (Arduino Due) and the programming term “Serial”, the existing attributes and methods
interface (programming port) as illustrated in of this class are listed for selection (Figure 4).
Figure 1. After this you have to configure the
appropriate virtual serial interface, which you At this point you could create or open a sketch
can find by looking in the Device Manager win- in the Arduino IDE in the usual manner and then
dow when the Arduino Due is connected to the import it into Atmel Studio. However, you now
PC with a USB cable. As in the Arduino IDE, the
serial monitor button is located to the right of
these settings. Adapter for SAM ICE +3V3

If the settings do not appear automatically, for This adapter is necessary for using
JTAG
example because the Arduino IDE software is the SAM ICE debugger/programmer SAM-ICE
2 1
not located in the default directory, you have to with the Arduino Due. 4 3
+3V3

select “Configuration Manager”. That opens the 6


8
5
7
JTAG_TDI
JTAG_TMS
JTAG
Arduino Due

window shown in Figure 2. There you have to It connects the 10-pin JTAG 10 9 2 1
12 11 JTAG_TCK 4 3
enter the correct folder location manually, since pinheader with 50 mil (0.05”; 14 13 JTAG_TDO 6 5
16 15 JTAG_RESET 8 7
no selection dialog is available. 1.27 mm) pin pitch on the Due board 18 17 10 9
20 19
Clicking the question mark on the menu bar in to the 20-pin JTAG connector on the
Figure 1 opens the Micro Explorer window (Fig- SAM ICE device. 130392 - 66

ure 3), which is the counterpart of the Solu-

4
www.elektor-magazine.com | December 2014 | 47

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

trollers. According to Figure 6 the AVR platform


is active, but the “Make file Name” location is
correct for the SAM toolchain of the Arduino IDE.
As usual with Atmel Studio, pressing the F7 key
compiles the project and pressing the F5 key (or
clicking the solid green arrow) downloads the
program to the board via the boot loader. You
have to select “Clean Solution” on the Build tab
(Figure 7), since that is the only way to ensure
that all files are compiled the same way as in
Figure 5.
The Solution Explorer
the Arduino IDE.
window of Atmel Studio. As previously mentioned, one of the main advan-
tages of Atmel Studio over a pure Arduino IDE
is shorter compilation time, which significantly
accelerates the iterative process of compiling,
testing and modifying program code. That’s
because the Arduino IDE always compiles all of
the program files, while Atmel Studio only com-
piles the files that have been modified. In most
cases this means that only the .ino file, which
Figure 6. contains the sketch code, is compiled. On the
The wrong platform is author’s PC the first compiler run for the Speed-
shown here, but everything Test sketch took 3.7 seconds, but the second run
still works fine. after a change was finished in just 0.23 second.

Debugging with the Atmel ICE


A real hardware debugger such as the Atmel ICE
makes software development a lot easier. All you
need to connect the Atmel ICE to the Arduino
Figure 7. Due is the basic cable that comes with the device.
Compiler run with the Clean The Arduino Due can be powered from the USB
Solution option. port or by an external AC adapter. The Atmel ICE
only needs the USB port.
have the option of creating new Arduino sketches There are two options for plugging in the debug
directly in Atmel Studio. After you create and cable. The SAM port is the right choice for the
save the SpeedTest sketch (see inset) in either of Arduino Due, with the other end of the cable
these two ways, the structure shown in Figure 5 plugged into the JTAG connector on the board.
appears in the Solution Explorer window. Now The current version of Atmel Studio (6.2) does not
you can open the sketch and edit it in the cus- support editing of Arduino sketches on an Atmel
tomary manner in Atmel Studio. From this point ARM platform, but there is a way to get around
on you don’t actually need to run the Arduino this. To use the Atmel ICE for debugging, simply
IDE. However, you should not delete it because launch a second instance of Atmel Studio. Then
it has to remain available on the PC. select Open -> Open Object File For Debugging.
It’s a bit confusing that the platform is shown as The compiled files generated by Atmel Studio are
“Active AVR” in the project properties (right-click located in the following folder under Windows 7:
SpeedTest: Properties Ž Build), at least in the
current version of Atmel Studio (6.2). Unfortu- C:\Users\xxxx\AppData\Local\
nately there’s nothing you can do about this. The VMicro\Arduino\Builds\SpeedTest\
platform is also shown as “AVR” under “Toolchain” arduino_due_x_dbg\
and “Device”. Nevertheless, everything works as
Figure 8. it should. When you select “Arduino Due” as the There you will find the file SpeedTest.elf. Now
Output files in the Solution board, the project is compiled in the same way as let’s open it for debugging.
Explorer window. with the SAM platform for Atmel ARM microcon- If the sketch was compiled and saved with the

5
48 | December 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Arduino & Atmel Studio

Arduino IDE, a copy of this file is also located in The actual structure of the downloaded Arduino
the debug folder for the sketch. It can be seen program can be seen in the Solution Explorer win-
in the Solution Explorer window of the code gen- dow, where the main.ccp file is selected and the
eration instance of Atmel Studio under “Output cursor is positioned on the first line of this routine
Files” (Figure 8).

Using the browse function, find and select the out-


put file SpeedTest.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
Figure 9.
open the debug project.
Dialog for selecting the
generated output file.
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 SpeedTest.ccp appears in the Solu-


tion Explorer window. This is simply the program Figure 10.
file of the sketch, which originally had the exten- Dialog for selecting the
sion .ino. Right-click the project name “Speed- device family and device
Test_Debug” to open the Properties window. type.

When the Atmel ICE is connected to the PC over


USB, the debugger can be selected under Tool ->
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 Ctrl-Shift-P or click 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.elf file directly
to the flash memory of the microcontroller. The
program starts running automatically after the
programming process completes.
Figure 11.
The true complexity of an
However, it is more efficient to use the Debug Arduino project can be seen
Ž Start Debugging and Break or the Start With- in the Solution Explorer
out Debugging command (or the corresponding window.
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
Figure 12.
programming function. When this error message
Downloading the complete program to the micro- appears after you modify a
controller takes roughly 1 second with the Atmel file, simply click “Reload” to
ICE, which is quite fast. dismiss the message.

6
www.elektor-magazine.com | December 2014 | 49

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

(Figure 11). As you can see, the SpeedTest.ccp


file is only a small part of the overall program,
which is why a full compilation takes so long.
The debugger gives you access to all the debug
functions of Atmel Studio, such as single-stepping
with F11, setting breakpoints with F9, defining
breakpoint conditions in the Breakpoint window,
and so on.
If you edit and recompile the SpeedTest.ino file
Figure 13.
in the first instance of Atmel Studio, the mes-
Oscilloscope screenshot
of the 150-kHz pulse sage shown in Figure 12 appears in the second
waveform. 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); //On
digitalWrite(TP1,0); //Off
Figure 14.
Microcontroller PIO register. With an oscilloscope, you can see a pulse wave-
form on this pin while the program is running,
with a pulsewidth of 2.35 µs and a period of
6.6 µs (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 digitalWrite is a cover name
Figure 15.
Oscilloscope screenshot of
for a bunch of C routines, as you can see by exe-
the 12-MHz pulse waveform cuting the program in single-step mode with the
generated by version 2.0 of debugger (F11 key). To actually achieve high
the program. processing speed, you have to avoid this over-

7
50 | December 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Advertisement
head. Fortunately, the Arduino programming language is not
a separate language, but instead a form of C with a GNU
compiler 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 TP1 = 7; //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 I/O View window of
the debugger (Figure 14) and click bit 23 of the PIO_ODSR YOU DESIGN IT – WE MACHINE IT
(set) register to set the pin high. To reset the pin, click the

Professional quality front panels


www.schaeffer-ag.de
same bit in the PIO_CODR (clear) register. In the main loop
you can simply use the instruction
From one piece and at a fair price! Simply
PIOC->PIO_SODR = 1<<23;
download our free Front Panel Designer at
to set the pin without any fuss or bother. www.schaeffer-ag.de, design your front
panel and order it directly.
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 #ifdef Direct is compiled, and otherwise the previ-
ous version with the slow digitalWrite instruction is com-
piled. Naturally, this change would also work in the normal
Arduino IDE.

Listing 1. Speed-Test.

//*******************************
//Speed-Test with Arduino Due
//*******************************

const int TP1 = 7; //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
digitalWrite(TP1,0); //Aus
}

8
www.elektor-magazine.com | December 2014 | 51

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

The result of this code optimization, as shown


Listing 2. Speed-Test 2.0.
in Figure 15, is stunning: the pulse waveform
//********************************* now has a pulse width of 23.2 ns and a period
//Speed-Test 2.0 with Arduino Due 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
#include „arduino.h“
such a bad idea.
//
// Summary
const int LED1 = 13; Working with Atmel Studio accelerates Arduino
int LED2 = 12; sketch development to a completely new level
int LED3 = 11; thanks to shorter turn-around times, since only
int TP1 = 7; //Testpin
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
#define Direct
worthwhile when you work with Atmel microcon-
trollers because they offer professional debugging
void setup() features and because downloading programs to
{ the microcontroller memory is significantly faster.
/* add setup code here */
Incidentally, you can also use Atmel’s SAM ICE
// set the digital pin as output:
instead of the Atmel ICE for ARM projects. With
pinMode(LED1, OUTPUT);
the SAM ICE hardware debugger and program-
pinMode(LED2, OUTPUT); mer, microcontroller programming speed can be
pinMode(LED3, OUTPUT); boosted by a factor of 4 because it can operate
pinMode(TP1, OUTPUT); at 8 MHz instead of 2 MHz. For this you need
// set output low the adapter described in the inset. If you are a
professional software developer, the expenditure
digitalWrite(LED1,0);
quickly pays for itself even if the device can only
digitalWrite(LED2,0);
be used with the AT91xx microcontroller family.
digitalWrite(LED3,0); (130392-I)
digitalWrite(TP1,0);
}
Web Links

void loop() { [1] Atmel Studio 6.2:


www.atmel.com/microsite/atmel_studio6
// put your main code here, to run repeatedly:
[2] Arduino IDE for Visual Studio:
#ifdef Direct
www.visualmicro.com
//x= state of PIO_SODR with bit 23 = 1
[3] Atmel ICE:
int x = PIOC->PIO_SODR | 1<<23;
www.atmel.com/tools/atatmel-ice.aspx
Review: www.elektor-magazine.com/140275
while (1){ //Only for testpurposes, don‘t exit this loop
[4] SAM ICE:
PIOC->PIO_SODR = x; www.atmel.com/tools/atmelsam-ice.aspx
PIOC->PIO_CODR = x;
}

#else
digitalWrite(TP1,1);
digitalWrite(TP1,0);
#endif
}

9
52 | December 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

C Modules
Software for Elektor Extension Shield,
Relay Board and more
By Jens Nickel (Elektor Germany)

Modular hardware enables us to create


plug-and-play prototypes rapidly; all we
ExtensionEFL_ECC_RS485.c need do is assemble predesigned build-
ing blocks. Exactly the same principle
can be applied to software, and the C
programming language is well suited
to this approach. This article showcas-
es some compatible software modules
BoardEFL_ArduinoUnoCore.c and demo applications for our Elektor
Extension Shield and three expansion
boards.

Elektor’s 2014 Project Generator double edi-


ExtensionEFL_Arduino_ tion introduced a compact plug-in board for
ElektorExtensionShield.c the Arduino Uno that contained a Display, two
user-definable LEDs, two pushbuttons and a
potentiometer or ‘pot’ [1]. Using this board, new-
comers can get cracking immediately and make
their first steps in programming microcontrol-
lers, for example adding digital outputs (LEDs)
and digital inputs (pushbuttons). More advanced
users will make use of two additional expansion
ExtensionEFL_
connectors on the board. The 10-pin Embedded
Communication Connector (ECC) provides TX/
EEC_Relay8.c
RX UART signals and two GPIO pins. Using a
flatcable you can hook up an RS-485 module for
example, enabling you to send and receive bytes
down longer c cables. Already developed is an
NFC gateway, enabling simple ASCII commands
to read and characterize NFC cards or communi-
cate with NFC-ready smartphones. Further ECC
modules are planned as well.

The 14-pin Embedded Extension Connector


(EEC) is also known as a Gnublin connector, as
it enables you to link up with the Gnublin mod-
ules from Benedikt Sauter and his team. Benedikt
has also defined the specifics of the connector,

10
56 | November 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


C Modules

although we should point out that the Elektor


Extension Shield employs only four of the 14 New file structure
pins (namely 3.3 V, GND and the two I2C lines). The EFL is now adapted additionally for larger modular projects, in which
However, most Gnublin boards [2] use only the several expansion boards are connected to (or chained in series with)
I2C pins, for example the Port Expander Board, a Controller board. For this purpose the Library needs to be extended
the Temperature Sensor Board, a board with eight somewhat and restructured compared with its previous state [5].
relays [3] and the ADC Board from the Septem-
ber 2014 edition [4]. • The hierarchical system of the Includes has been disentangled. Only
Header files from the Common folder are now integrated throughout.
Software modules These files are identical in all EFL projects, regardless of which boards
In the BASCOM-oriented Microcontroller Boot- and Controllers are used.
Camp course that concludes in this edition vet- • To this end a new Header file is placed in the Common folder
eran author Burkhard Kainka has developed some (ControllerDefinesEFL.h). It now includes all Function definitions
interesting applications for the Elektor Extension of the Controller API, which of course are always identical. The
Shield. More of these will appear in Elektor from Controller-specific Header file (previously ControllerEFL.h) now
time to time. includes only Controller-specific definitions, such as those for the
Register.
One thing that was lacking till now was soft- • Instead of ControllerEFL.h/.c and/or BoardEFL.h/.c we now
ware support for C. This language is particularly provide meaningful names for the Controller and board-specific code
well suited for modular software projects. Once files. The file that implements the Controller API for the ATmega328,
developed and tested (either by yourself or by is now called ControllerEFL_ATmega328. The file extracted
third parties), software modules can be used from the wiring connection to the Arduino Uno board is called
again and again in your homebrew projects. This BoardEFL_ArduinoUnoCore.
shortens development time enormously and in • We can now integrate several extension boards into our project,
extreme cases you can achieve a major, func- since the relevant code files all have differing names instead of
tioning application in minutes. And should those ExtensionEFL.c/.h . For instance:
project requirements alter, for instance if an addi- -- ExtensionEFL_Arduino_ElektorExtensionShield.c/.h
tional RS-485 interface becomes necessary, you -- ExtensionEFL_ECC_RS-485.c/.h
can create a compatible software solution just -- ExtensionEFL_EEC_Relay8.c/.h
as rapidly. The type of expansion connector is always shown between the
underscore symbols.
Hardware-wise we can now devise a functioning
• The Board-Init Functions that incorporate the onboard wiring
system from modules that need merely plug-
connection in the Tables and make ready the Peripheral units are also
ging together. Once you have stacked the Elektor
given more specific names, for example ExtensionEFL_Arduino_
Extension Shield onto an Arduino Uno board, you
ElektorExtensionShield_Init(0) in place of ExtensionEFL_
can plug in your choice out of an RS-485 mod-
Init(). To make this consistent, the Controller-Init Function is
ule, a relay card or an ADC board. We shall now
now, for example, ControllerEFL_ATmega328_Init() instead of
apply the same modular principle to the software;
ControllerEFL_Init().
for an application with defined requirements we
An initialization of the Controllers and all boards could now look like
need simply assemble the corresponding code
this for example:
modules into a software project. Ideally each
-- ControllerEFL_ATmega328_Init();
hardware module will have its associated soft-
-- BoardEFL_ArduinoUnoCore_Init();
ware module that can be used without alteration,
-- ExtensionEFL_Arduino_ElektorExtensionShield_Init(0);
regardless of in which particular set-up the hard-
-- ExtensionEFL_ECC_RS-485_Init(2);
ware interacts. Take for example the code for the
-- ExtensionEFL_EEC_Relay8_Init(3);
Relay Expansion Board; it remains unchanged
• The Init Functions of the Expansion boards are now augmented
regardless of whether we hook up the relays to
with the consecutive Block number of the expansion connector to
the Elektor Extension Shield, the Xmega Board
which they are attached. In this way the wiring connection (from
or the Elektor Linux Board.
the Controller pins through to the furthest Peripheral) is represented
correctly in the EFL-internal Tables. It is now also possible to ‘chain’
Pretty close to perfection
Expansion boards in series as in the present case (for this see also
Using the programming language C and the
Embedded Firmware Library (EFL) described in the main article and Figure 1).

11
www.elektor-magazine.com | November 2014 | 57

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

RELAIS
ing to the Arduino-Uno board has the name
ARDUINO BoardEFL_ArduinoUnoCore.
#0
RS485
#2 #2 #3 #3
• We can now use several extension boards in
our project, since each of the corresponding
code files has a different name, for example:

#1
ExtensionEFL_Arduino_
SHIELD
ElektorExtensionShield.c/.h
140328 - 17 ExtensionEFL_ECC_RS-485.c/.h
ExtensionEFL_EEC_Relay8.c/.h

Figure 1. Elektor [5] we can get extremely close to the


Chaining expansion boards: ideal just described, as we shall now show. Up • The Init Functions called up initially are also
the Extension Shield is till now you could use the EFL only for a Duo named specifically. This is the initialization of
plugged into two connector equipped with a Controller Board and an Exten- the Controller and all the boards for the first
strips on the Arduino Uno
sion Board. So that other expansion boards can be sample application discussed next:
(#0 = digital pins, #1 =
used in a project, the Library had to be extended
analog pins). Connectors
#2 (ECC) and #3 (EEC) are and restructured somewhat. To avoid boring the ControllerEFL_ATmega328_Init();
still available for use, being hands-on practitioners among our readers with BoardEFL_ArduinoUnoCore_Init();
linked through and repeated all the details, we have placed the full explana- ExtensionEFL_Arduino_
on the Shield. tion in a separate text box. Here in brief are just ElektorExtensionShield_Init(0);
the most important alterations:
ExtensionEFL_ECC_RS-485_Init(2);
ExtensionEFL_EEC_Relay8_Init(3);
• Previously a file pair by the name of Con-
trollerEFL.h/.c contained Controller-spe- The number of the first expansion Port connected
cific source code that made standard- is given together with the Init Functions of the
ized Functions available for activating the expansion board; this number is incremented
inputs and outputs of each Controller, for during the initialization of the board (Figure 1).
example IO_SetPinLevel(…). A file pair, The Extension Shield is installed on the Arduino
always called BoardEFL.h/.c, displayed the Uno, which defines two expansion Ports; these are
onboard wiring connections (which the appli- assigned the numbers #0 (digital pins) and #1
Figure 2. cation developer no longer needs to know). (analog pins). The Extension Shield is connected
Application 1: Eight relays Instead of the uniform designations these to #0 and #1 and has onboard two additional
can be operated either files now have meaningful names. The file expansion Ports, #2 (ECC) and #3 (EEC). To the
locally via a user interface responsible for the ATmega328 is now called first of these we connect the RS-485 module and
or remotely via RS-485. ControllerEFL_ATmega328. The file belong- to the second the relay module.

(Remote) Control of relays


We have prepared three demo projects for Atmel
Studio 6 that you can find in the download data
for this article [6]. Incidentally a Configurator for
the PC is already in development; this automati-
cally assembles and integrates the files necessary
for an EFL project in Atmel Studio. This leaves
you only the task of indicating which boards you
plan to use in the project.

Let’s begin with the first project, a small control


application. Eight relays can be switched locally
using a user interface; they can also be controlled
remotely by a PC using a Terminal program. An
Elektor Extension Shield is plugged on top of an

12
58 | November 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


C Modules

Arduino Uno; the Gnublin PCB with eight relays


is connected to this with some flat cable (Fig-
ure 2). The RS-485 ECC module is an optional
extra, also connected to the Shield; the con-
nection then goes over RS-485 (two wires plus
ground) to an RS-485-to-USB converter and the
PC. The application will also work if you link the
Arduino Uno direct to a PC using USB.

The software can be found in the download pack-


age in the ElektorShieldRelay folder. After click-
ing on ElektorShieldRelay.atsln the project
opens in Atmel Studio (Figure 3). On the right, in
Solution Explorer, you can see the integrated files.
In all cases you should be able to see a folder
called Hardware. As well as the files mentioned
above for the Controller, the Controller board
and the expansion board you will also find the
new BlockEFL files with the Low Level Functions
for the RS-485 driver, the digital outputs and
inputs and the Display (see box-out ‘BlockEFL
files’). Advanced users should check out the code
in the file ExtensionEFL_Arduino_ElektorEx- verted into the character strings in Block Protocol Figure 3.
tensionShield.c (Figure 3). This code records format [7] that are received via the UART. The Relay control operation in
the peripheral Blocks located on the Shield in the Function ADCSimple_GetRawValue(0, 0) returns Atmel Studio 6. The code
indicates the initialization of
EFL-internal Block Table (Figure 4). From now the value of the ADC input 0 in ADC Block #0 (the
the Extension Shield.
on the buttons on the board respond to the Block pot is connected here). The value can amount to
number #0 and the LEDs to Block number #1, as 0...1023 (10 bits); we can reduce this to 7 bits
there is already an LED mounted directly on the by shifting them to the right, in order to obtain
Arduino board (addressed using Block number a figure between 0 and 7. This enables us to
#0). For the pot an ADC Block #0 is provided, select one of the eight relays from the setting
then comes the Display with the number #0. of the pot. The selected value is shown in line 0
Finally the wiring to the ECC and EEC connectors of the Display.
is displayed, with two new Blocks provided for
the connectors (#2, #3). The entries are then The Function ButtonEventCallback(…) contains
used once more by the code of the ECC and EEC code that is carried out when a pushbutton is
modules. Last of all, check out each peripheral pressed. Which of the two buttons was pressed
Figure 4.
unit in the Table to see which Controller pin it is is determined using the variable ButtonPosition
All peripherals can be
connected to. (0 or 1). If the left-hand button (0) is pressed,
addressed conveniently and
we deactivate the selected relay, whilst pressing uniformly using their Block
Let’s now examine the main program in the file the right-hand button (1) activates the relay. As numbers.
ElektorShieldRelay.c. The routine Appli-
cationSetup() contains all the initializations
RELAIS
from the Controller via the boards as far as the ARDUINO
RELAY#0
Libraries. Assuming your hardware setup does
CONN#0
not change, you can leave the whole bunch RS485
LED#0 LED#1
BUTT#0
UART#0 CONN#2 CONN#3
untouched.
DISP#0

Short code
The application itself can be viewed in Listing 1. CONN#1
ADC#0

In the Function ApplicationLoop() you will see SHIELD

all the commands that need to be reiterated each


140328 - 12
time. First the pressbuttons are polled, then con-

13
www.elektor-magazine.com | November 2014 | 59

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

BlockEFL files
Up till now BoardEFL and ExtensionEFL files have still included the so-called Low Level/Block Functions, such as for example
the Function

void Display_SendByte(uint8 DisplayBlockIndex, uint8 ByteToSend, uint8 DATABYTE_COMMANDBYTE)

which is based on the wiring interconnection between the


Controller and Display (4-bit or SPI as appropriate). A Display APPLICATION
Library such as DisplayEFL then needs only to ensure that
the correct bytes are sent to the Display. The code there is LED
DISPLAY UART LIBRARIES
BUTTON

COMMON
independent of which particular route the bytes take to reach
the Display. This Block Function must be defined once in the BOARD BLOCK BLOCK BLOCK
DISPLAY IO UART
project if a Display is provided on any of the boards. HARDWARE
LAYER
Logically we therefore provide a dedicated file pair in the CONTROLLER
Hardware folder for the Low Level/Block Functions required
by the Display. If a Display is used anywhere in a project, HARDWARE
you need to integrate BlockEFL_Display.h/.c in addition. A 140328 - 14

different BlockEFL file is responsible for the RS-485 Functions.


Block Functions for digital outputs and inputs, such as for
instance SwitchDigitalOutput(uint8 BlockIndex, uint8 Position, uint8 ON_OFF) are also extracted from the
BoardEFL file and relocated into a new file BlockEFL_IO.
The Board files now contain normally only the Init Functions that define wiring and integrated Peripheral/Blocks like, for
example, making the Display ready. For this purpose the Function

void Display_BoardSetup(uint8 DisplayBlockIndex);

is called up there, now located in BlockEFL_Display.h/.c.


Overall, you now have to deal with a greater number of files but the modularity of the EFL has been further improved.
Already in development is a Project Configurator, which assembles and integrates the files necessary for a project
automatically.

the Function SwitchRelay(…) directly demands a


0 = OFF or a 1 = ON as its third parameter, the
code turns out agreeably short and to the point.
Info on these and the other EFL Functions is in
the Doxygen documentation (click on Index.htm
in the download).

Using the Block Protocol [7] you can control the


relays remotely from a Terminal program. The
command R 0 2 + <CR> activates the third
relay in Relay Block #0 (as always we count up
from zero, 0, 1, 2…). R 0 2 - <CR> deactivates
it again. With L 0 0 + <CR> we can switch on

Figure 5.
You can display the EFL Tables using a Terminal program.
The Blocks are set out centrally.

14
60 | November 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


C Modules

the LED located directly on the Arduino. L 1 0


Listing 1. Relay (remote) control.
+ <CR> and L 1 1 + <CR> are the correspond-
ing commands for the LEDs on the Extension uint8 RelayPosition;
Shield. Do also try the command x <CR>; you
will then have on your screen the content of the void ApplicationLoop()
EFL Table. At the centre you will see all the rel- {
evant Blocks (Figure 5). ButtonPoll(0);
BlockProtocol_Engine();
Precise measurement
For our second application we remove the relay
RelayPosition = ADCSimple_GetRawValue(0, 0) >> 7;
board and substitute the 16-bit ADC board that
Display_WriteNumber(0, 0, RelayPosition);
we featured in the September issue [4]. As men-
tioned in that article, we link the output A3 on }
the lower Arduino connector strip (replicated on
the Shield) using a flying lead to the input AIN0
of the ADC board (Figure 6). Our task now is void ButtonEventCallback(uint8 BlockType, uint8
to digitize the setting of the pot also using the ButtonBlockNumber, uint8 ButtonPosition, uint8 Event)
accurate external ADC. {
if (Event == EVENT_BUTTON_PRESSED)
Double clicking on ElektorShieldADC.atsln {
reveals the source code. As seen in Solution
ToggleLED(1, 0);
Explorer, instead of the two files ExtensionEFL_
SwitchRelay(0, RelayPosition, ButtonPosition);
EEC_Relay8.c/.h we now have two files Exten-
}
sionEFL_EEC_ADCModule16bit.c/.h in the proj-
}
ect. In addition the files ADC_ADS1x1xEFL.c and
BlockEFL_DeviceRegister16.c have appeared
now. BlockEFL_DeviceRegister16.c in the
Hardware folder contains Low Level Functions good multimeter you will discover the external
for addressing an I2C chip, featuring 16-bit reg- ADC measures to a high level of accuracy.
isters. ADC_ADS1x1xEFL.c takes care of the cor-
rect compilation of the bytes, which are written This application also provides remote access Figure 6.
Application 2: External
in these registers (the Library of my colleague using the Block Protocol. The command A 0 0
16-bit ADC on the Arduino
Clemens Valens is adapted to the EFL here [4]). # <CR> causes the Arduino to return the value
Uno. The voltage on the pot
just sampled by the internal ADC in hex charac- is returned across the cable,
Application developers don’t have to be concerned ters. A 1 0 # <CR> returns the last value of the enabling the readings of the
with all this. The only thing they need to know is external ADC. The indications are quite different internal and external ADCs
that after initialization of the boards a further ADC because we are now dealing with raw values and can be compared.
Block with the number #1 is created (Figure 7).
You can now access the external ADC exactly as
you would the internal ADC of the Controller. The
application library ADCSimpleEFL.c for instance
makes available the Function ADCSimple_GetMil-
livoltValue(..), which can provide you with
the voltage in millivolts on an analog input of a
particular ADC Block.

The actual application code is located in the file


ElektorShieldADC.c, the critical function being
printed in Listing 2. Next up we need to find
out what the application actually does: the volt-
age on pin A3 of the Arduino is digitized by both
the internal and external ADCs and displayed
on-screen. If you check out the voltage with a

15
www.elektor-magazine.com | November 2014 | 61

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Virtualization
Port expanders and external A-to-D converters are two The concept of ‘Virtualization’ is now broadened to analog
sample applications for chips that extend the capabilities of inputs. In our case the external ADC is located on the
a Controller. Frequently these chips are addressed via an EEC/Gnublin ADC Expansion board, so the code in file
I2C Bus or some other serial interface. ExtensionEFL_EEC_ADCModule16bit.c must take over
the activation of its ADC. When the board is initialized with
A modular prototyping library should, as far as possible, the Function ExtensionEFL_EEC_ADCModule16bit_Init(…)
be based on the hardware used. For someone developing the external ADC is integrated into the EFL Tables like
an application (or a Library that activates Peripherals) an internal ADC (in our case with the Block number #1),
it should be immaterial how the wiring tracks run on where, however, it is assigned to the virtual Port 0x40. In
the board or to which Controller pins the Peripheral is addition the I2C interface is made ready. Furthermore the
connected. Ideally the developer should also not need to Function Virtual_ADC_GetValue(…) is notified to the
know whether an input or output is connected to a genuine Controller code.
Controller pin or merely to a Port expansion chip. We
can solve that problem by assigning to the Controller in Using the Function ADCSimple_GetRawValue(uint8
addition to its Ports 0, 1, … etc. some extra ‘virtual’ Ports ADCBlockNumber, uint8 ADCPosition) users now have
that begin with the number 0x40 = 64, so as to be able to access to an ADC pin in a specific ADC Block, independent
differentiate these from ‘real’ Ports. of the connection to the Controller. The Function directly
If for example you wish to activate a relay connected to a calls up the Controller Function ADC_GetValue(…). The
Port expansion device, then access to the relay from the Controller refers to the EFL Tables and on account of the
RelayEFL Library will be forwarded perfectly normally to high Port number recognizes that an internal ADC is not
the Function SwitchDigitalOutput(…), located in the file intended but instead it should call up the Function Virtual_
BlockEFL_IO.c. This Function refers in the EFL Tables which ADC_GetValue(…), located in the code file of the Expansion
Controller Port and pin the relay belongs and calls up the board. This results in giving access to the external ADC over
Function IO_SetPinLevel(…) in the Controller file. In the I2C.
Tables a Port 0x50 is recorded for the relay and normally
this would be the end of it, as the Controller is unaware As well as the Function ADC_GetValue(…) our application
of any Port 0x50. However, for such situations when the also virtualizes the Function ADC_GetParameter(…), with
relay board is initialized, a special Function of the relay which the resolution and voltage range of an ADC can
board code is passed to the Controller code that is called be read off. In this way ADC values can be calculated in
up in cases like this. This same Function then sends the millivolts.
corresponding I2C commands to set the output pins of the
Port expansion unit located on the board.

not numbers of millivolts. To avoid inflating the Mini Protocol


Block Protocol library unduly, we have foregone Given that we can already calculate the millivolt
having a Function for converting ADC values into readings in the application, couldn’t we simply
millivolts. call them up using the UART?
Absolutely! We just need to concoct a dedicated
mini Protocol. It we transmit 0 <CR>, then we
ARDUINO receive back the value of the internal ADC in
CONN#0
millivolts. Typing 1 <CR> should arrange that
LED#0 LED#1 ADC-BOARD
RS485 BUTT#0
UART#0 CONN#2 CONN#3 ADC#1

DISP#0

ADC#0
Figure 7.
CONN#1
Internal and external ADCs can be addressed using the
SHIELD 140328 - 13 same Functions, with the Block numbers #0 and #1 used
for differentiation.

16
62 | November 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


C Modules

the Arduino send back the value of the external


Listing 2. Measurement using internal and external ADCs.
ADC. Now we can compare both values directly
in the Terminal program. void ApplicationLoop()
{
Listing 3 shows the relevant code (project Elek- ButtonPoll(0);
torShieldADCMiniProtocol.atsln in the down-
BlockProtocol_Engine();
load). ReceiveRingbuffer contains the address
of the receive ring-buffer, where the characters
uint16 ADCValue1 = ADCSimple_GetMillivoltValue(0, 0);
are written. These then reach the Arduino via
Display_WriteNumber(0, 0, ADCValue1);
the UART (UART Block #0).
The millivolt value is converted into hex digits in
uint16 ADCValue2 = ADCSimple_GetMillivoltValue(1, 0);
the application routine SendMillivolt(…) and
Display_WriteNumber(0, 1, ADCValue2);
sent forward via the UART #0.
}

In an upcoming issue we will introduce the Con-


figurator, with which you can generate an EFL
project yourself. We’ll also provide simple instruc- Listing 3. Reading values with a mini Protocol.
tions for writing your own board file. Stay tuned! void ApplicationLoop()
(140328) {
ButtonPoll(0);
//BlockProtocol_Engine();

uint16 ADCValue1 = ADCSimple_GetMillivoltValue(0, 0);


Display_WriteNumber(0, 0, ADCValue1);

uint16 ADCValue2 = ADCSimple_GetMillivoltValue(1, 0);


Display_WriteNumber(0, 1, ADCValue2);

while (Ringbuffer_IsEmpty(ReceiveRingbuffer) == FALSE)


{
uint8 ReceivedChar =
Ringbuffer_GetByte(ReceiveRingbuffer);
if (ReceivedChar == ‘1’)
{
SendADCValueOverUART(ADCValue2);
}
if (ReceivedChar == ‘0’)
{
SendADCValueOverUART(ADCValue1);
}
}
}

Web Links void SendADCValueOverUART(uint16 ADCValue)


[1] www.elektor-magazine.com/140009 {
uint8 sd[3];
[2] www.elektor.com/development/gnublin/
[3] www.elektor-magazine.com/130157 sd[0] = (ADCValue & 0xFF00) >> 8;
[4] www.elektor-magazine.com/130485 sd[1] = ADCValue & 0x00FF;
sd[2] = 13;
[5] www.elektor-magazine.com/120668
[6] www.elektor-magazine.com/140328 UARTInterface_Send(0, sd, 3);
[7] www.elektor-magazine.com/130154 }

17
www.elektor-magazine.com | November 2014 | 63

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Extremely Low Frequency


(ELF) Receiver
Arduino + ADC = ELF

By Kurt Diedrich If you Google


(Germany)
the terms ELF,
ULF, or VLF it
transpires that the
lowest frequencies of all electro-
magnetic interference (EMI) signals
are generated by electrified railways and not a lot more
beyond this. Wrong! You can in fact receive some extremely interest-
ing signals between 0 Hz and the ‘railway’ frequency of 162/3 Hz. Using the receiv-
er described here with an ADC module described in a separate article and some
free PC software it is possible to receive and make recordings of these signals.

It had always fascinated me what I might hear—or ten in Europe where the AC supply frequency is
rather see on an oscilloscope—if I could connect 50 Hz but exactly the same methods will work
a pick-up coil, with a couple of hundred turns on in territories where the line frequency is 60 Hz.
it, to an extremely sensitive amplifier. A dozen Please read ‘60’ wherever you see ‘50’ from now
or so years ago I decided to turn this supposition on, if you live in a 60 Hz country. Ed.]
into fact using modern electronics. Eventually, after I submitted my received data to
The first circuit I constructed for this purpose FFT-versus-Time analysis, it became very clear to
differed from the version presented here only me that that this ‘wriggling about’ on the screen
by having a cruder filter and a somewhat old- was the result of recurring signals of typical struc-
er-fashioned method of analog to digital con- tures, which could be resolved only if they could
version. To my surprise there appeared on the be compressed over prolonged periods of time.
monitor screen more than the power frequency They were also audible if played back at higher
hum that I was expecting but unfortunately the speed, sometimes reminiscent of animal sounds
confused serrations of the complex time signals or teletype transmissions on the short waves. In
did not allow me to draw any conclusions from any case, all this was sufficiently interesting to
about their composition. [this article was writ- keep me occupied with it ever since. Readers who

18
8 | October 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


ELF Receiver

are interested will find further detailed informa- be connected to other recording devices, all the
tion at the blog vlf.it [3], which is a platform for time keeping in mind that signals below 16 Hz
enthusiasts involved with receiving and experi- will be attenuated heavily by PC sound cards.
menting in the ELF and VLF bands. I have pub- The circuit is made up from a combination of a
lished a number of articles there on this theme highly sensitive voltage amplifier and a steep
along with many screen shots. (36 dB per octave) Sallen Key low-pass filter with
Among other things, we need to understand that a cut-off frequency of approximately 21 Hz. The
supply transformers in residential areas radiate receiver has the task of amplifying extremely
extremely weak magnetic waves between around weak magnetic waves in the frequency range
0.3 Hz and 25 Hz. These are up to 1,000 times from 21 Hz down to (almost) 0 Hz and filtering
weaker than the interference fields produced by out line hum interference in the process. Figure 1
the 50 Hz AC supply. To receive the desired fre- shows the schematic for this receiver, which is
quencies without interference, we need to filter made up from the functional groups that follow.
out the 50 Hz (60 Hz) supply hum as early as
possible ahead of the main amplifier in order to Linearizer and preamp
avoid over-driving the receiver. The extremely weak (in the microvolt region) AC
signals of interest here are picked up with a coil
The circuit and once processed and optimized in a combi-
The receiver described here operates in conjunc- nation of preamplifier and low-pass filter (IC1),
tion with the ADC module described in a separate they are directed to the Sallen Key low-pass filter
article, an Arduino Uno and some free—that goes that follows. This simple upstream low-pass filter
without saying—recorder software for the PC. This (a pre-filter so to speak) is necessary specifically
combination makes it possible to detect, display for attenuating any 50 Hz line frequency interfer- Figure 1.
and log weak alternating currents and/or alter- ence in relation to the wanted signal to prevent Schematic of the ELF
nating magnetic fields at frequencies down to less overloading that might generate a square-wave Receiver (without Data
than 1 Hertz. The receiver output can additionally signal between the maximum output voltages Logger).

R7
56k K2(S1)
1 2
R6
C1 3 4
120k TP1
5 6
R5 IC3 = TL074
10n 390k
R2 C6
10M R4 C4
9
470k C2 1u TP2
K1 6 8
IC1
8

R1 330n R12 R13 IC3C


2 2 7 10
IC2
8

100k R3 220n R10 R11 IC3B 18k 150k


1

6 2 1 5
OP07 10k R8 R9 IC3A 18k 220k
1

3 6 3
Coil OP07 22k 180k C7 TP3
3 C5
C3 22n
47n
68n
IC4
IFX25001TS V50 +5V
S2 L1 L2 +12V R16 P1
1 3
47k
100u 1 6 100u
+VIN +VOUT C22 C20 C18 1M
C8 C9 R15
13 K3
2

BT1 MOD1 10u 100n 47u L4 100k


C28 C27 C26 C25 C24 C17 C16 14
5 63V 25V 47u 47u IC3D
6V COM 25V 25V 12
R14
100u 100n 1000u 100u 2u2 C23 C21 C19 100n 100n
25V 16V 25V TMA0512D 2 x 47u
100k

2 4 0Ω6
-VIN -VOUT 10u 100n 47u 900mA
63V L3 25V

100u -12V
+12V +12V +12V +5V

R17
C10 C12 C14
1k5

7 7 4
100n 100n 100n
IC1 IC2 IC3 D1
C11 C13 C15
4 4 11

100n 100n 100n Power


140035 - 11
-12V -12V -12V

19
www.elektor-magazine.com | October 2014 | 9

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

of the op-amp. This could occur were the coil The stage built around IC2 is a well-known ‘stan-
to be placed close to a power cable in which a dard’ circuit involving an inverting amplifier. The
heavy current was flowing. The circuitry associ- gain factor can be varied by selecting one of sev-
ated with IC1 has a second function: the char- eral feedback resistors. This feature is absolutely
acteristics of the coil at the input of the circuit necessary since completely different intensities
mean that low frequencies are attenuated appre- of the received signal may arise, according to
ciably, so that the amplitude of received signals the position of the receiver. R4 is not a built-in
in the region of zero Hz is weakened increasingly. part of the selector switch, ensuring that there is
We can compensate or ‘linearize’ this to a large always some degree of negative feedback, even
extent using the effect of capacitor C1 in paral- when the switch settings are open-circuit. This
lel with R2. Figure 2 shows the amplification at has the advantage that at the moment of swi-
the output of IC1. tchover, when the switch contact ‘hangs in mid-
air’ for a very brief timespan, no interference
pulses appear on the receiver output.
The gain or amplification of the inverting ampli-
Audio Precision
+24 fier arises from the quotient negative feedback
+23
resistance divided by the upstream resistor:
+22

+21

+20
V = Rg/Rv
d +19
B
r +18

A +17 By switching from R7 down to R4 alone we have


successively (approximate) gain settings of 5,
+16

+15

+14 10, 21 and 47, the last of these values being


Figure 2.
+13
when the three switches or jumper links are all
+12

Amplifier flatness at the


10 12 15 20
Hz
22 25 30 32 35
140035 - 54
open-circuit.
output of IC1.
Filter
The remaining four op-amps are combined in a
+10
Audio Precision
single IC, the TL074. IC2A to IC2C together form
+0
a Sallen Key Filter with fast roll-off providing 36
-10

-20 dB per octave in total. The elevated level of the


-30

-40
50 Hz signal relative to the desired signal makes
d
B
-50 this filter extremely necessary, to prevent over-
r -60

A -70
loads. To learn more about Sallen Key Filters you
-80
can find the desired background information in
-90

-100 the technical literature and on the Internet [2].


The cut-off frequency of the filter is, precisely
-110

-120
Figure 3. -130
stated, 21.5 Hz, which is far enough removed
10 20 50 100 200 500 1k
Filter IC3 achieves a slope of Hz 140035 - 55

from the interfering 50 Hz and is still outside the


around 36 dB per octave!
desired reception range.
You should stick to the values given for the capac-
Audio Precision itors and resistors as closely as possible, as the
required transfer characteristic cannot be guar-
+0

-10

-20

-30
anteed. Figure 3 shows how steep the flanks of
-40
the resulting filter are (measured at the output
-50

d
-60 of IC3C).
B -70
r
-80
A
-90

-100
High-pass and final stage
-110 At high levels of gain (according to the setting
-120

Figure 4. -130 of P1 up to about 50,000) it’s possible that even


The common-mode choke
-140

-150
quite small offset voltages could nevertheless
6 10 20 50 100 200 500 1k 2k

reduces interfering noise by Hz 140035 - 56 be sufficiently large to shift the output signal by
up to 40 dB. several volts into the positive or negative regions

20
10 | October 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


ELF Receiver

and become an undesirable disruption. To avoid


this, a high-pass filter (C8+C9/R14) is provided
between the filter output (IC3C) and the input to
the amplifier stage IC3D following, with a cut-off
frequency arranged to lie well below the target
range. In this way the filter does not affect the
frequency response of the received signals. The
voltage at the the output of IC3D is thus always
symmetrical around zero. Trimpot P4 is used to
adjust the total gain of IC3D between 0.5 and
about 10.5. In conjunction with the switchable
pre-filter stage this should suffice for well-nigh
all user situations.

Powering the circuit


Power connections are provided for 6 V recharge-
able (or plain) battery operation. Initially the
voltage is reduced to 5 V and stabilized in IC4,
to suit the needs of the TMA0512D converter that
follows. This converter changes the input voltage
of 5 V into two complementary output voltages
of 12 V, used for powering the op-amps. Do not so thin that it would snap instantly if handled Figure 5.
omit any of the chokes and capacitors shown in roughly. The author’s home-made
the schematic of the power supply section, as During signal reception the coil must lie flat on coil winding machine.
these are absolutely necessary to reduce interfer- a non-metallic surface, as far away as possible Smaller versions will suffice
ence from electrical noise. Figure 4 shows, for from any AC power cables with current flow- for practical applications.
example, the beneficial effect of using the com- ing through them. Important: on account of the
mon-mode choke L4; this suppresses noise in the Earth’s magnetic field, the receiver should be
relevant frequency range by around 30–40 dB! operated only when the coil is not subjected to
If you prefer to power the receiver using an AC any movement or agitation.
adapter rather than batteries you can connect As an alternative to the pickup coil, the receiver
a 6-V wall wart power adaptor of the necessary can also be used with electrodes, consisting of
amps rating. metal probe spikes about 8 inches (20 cm) long,
pushed into the ground at a distance about 7 feer
Coil and electrodes (2 m) apart. In this way you can detect alternat-
To detect weak magnetic fields a sensitive receiv- ing currents in the prescribed frequency range
ing antenna is necessary, so we should connect a present in the Earth’s surface.
coil with around 2,000 to 4,000 turns of as large
a diameter as possible. This does not have to be Safety warning: If you are working with ground
as full-blown an affair as the one shown in Fig- electrodes bear in mind the risk of rogue AC
ure 5; a diameter of 12 to 20 inches (30 – 50 cm) power voltages in the soil. For this reason it is
will be perfectly adequate (to begin with). The vital to use a 1:1 microphone transformer (iso-
sensitivity of the coil (not to be confused with lating transformer) on the input of the receiver
its inductance!) increases linearly with the area whenever the receiver (or any other device con-
enclosed by the coil former and the number of nected to it) is powered from the AC supply. I
turns. The coil should be ring-shaped and if you have experimented with an example made by
buy the wire from a specialist supplier coiled in a the firm Jensen that has proved to be absolutely
roll [3], you can create your coil rapidly and eas- ideal (type JT-11P-1). A variety of suitable types
ily using a coil-winding machine made at home are shown on this American firm’s website [4].
from an old Erector or Meccano outfit. Use unscreened cable to connect the ground
Enameled copper ‘magnet’ wire of 30 AWG spikes to the transformer, the secondary side
(0.25 mm) diameter turned out to be a partic- of which is hooked up to the receiver input in
ularly good choice for making the coil. It is not place of the coil.

21
www.elektor-magazine.com | October 2014 | 11

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

The author’s prototype can be seen in Figure 6,


with Figure 7 showing the test build made with
stripboard in Elektor Labs.
Once you have finished the construction and test-
ing, the alignment of the receiver with the oscil-
loscope can begin. Hook the coil up to the input,
arm yourself with a strong magnet (such as one
from a loudspeaker) and investigate each of the
outputs of the op-amps in succession. At the out-
put of IC2 the line hum (so far only pre-filtered
and receivable everywhere) should not exceed
the 50 % overload limit. If the options available
at K2/S1 are insufficient for this, then the value
of R3 should be increased.
As you investigate each successive IC output,
the 50 Hz (60 Hz) sinewave components should
become ever weaker. Now set the oscilloscope
to 1 V/Div and move the magnet to and fro by
hand at a distance of two meters from the coil,
once or twice a second. You should now be able
to observe clear deflections up to the clipping
limit. It should also be possible to detect a slight
ripple even without moving the magnet, result-
ing from ambient signals (unless your home is
Figure 6. Alignment, connection and testing in the middle of a forest). Next adjust P1 so that
The author’s first prototype. A printed circuit board layout is not provided for the peak values of this ripple amount to no more
The Arduino data logger is the circuit of the ELF receiver, so readers inter- than ±1 V and lie within the optimum range of
also visible in the case.
ested in replicating it must resort to self-help or the A-to-D converter. The output signal should
simply assemble the small number of compo- be free of any offset voltages whatsoever. Also
nents involved on a piece of perf-board or strip the line frequency sinewave oscillations should be
board (Vectorboard; Veroboard). Programs like barely detectable now. At output K3 you should
Figure 7.
Test build signed off by LochMaster from Abacom or the free Blackboard now have a pure AC signal for downstream pro-
Elektor Labs. [5] will be of assistance for laying out the board. cessing by the ADC.

Installation and
operation of the recorder
Now connect the ELF receiver to the 16-bit Data-
logger module described in the September 2014
edition of Elektor [13]. The ADC samples the
signal with a resolution of 15 bits and a sampling
rate of around 112 Hz. The article also explains
how the ADC module can be connected to an
Arduino Uno, which accepts the digitized data
using a simple program (Sketch) and relays this
to the PC and the recording software.
The recorder software is written in the Processing
programming language [12], which resembles
C. Curly brackets are used for code blocks; each
instruction must be closed off with a semicolon.
The programming environment is very simple:
just open the Editor and write the source text.
Then click on the Start button and you’re rolling.

22
12 | October 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


ELF Receiver

What is ELF?
ELF signals are a mysterious and, to some
degree, myth-ridden subject that amounts in
reality to nothing more than electromagnet-
ic waves of extremely low frequency (hence
ELF) from 3 Hz to 30 Hz. Because commercial
radio transmissions do not exploit such low
frequencies, it is naturally fascinating to inves-
tigate what is going on in this profound realm.
Wow! This signal occurred on one single occasion
over a night in September 2013. Duration around
In residential areas many of the signals de-
one hour. Recording made with electrodes. Frequency
tectable with the receiver described here
range: 0 to 20 Hz.
clearly take the form of magnetic waves ra-
diated by supply transformers at the local
substation. The sprawling network of metallic
conductors (ground connections, water and
gas pipes, etc.) evidently behave like a vast
underground antenna that gathers up the
weakest low-frequency alternating currents
flowing in the ground, wherever they may
arise from, and transports them to a common
connection point at the local substation. Here
A square-wave signal of 1.6 Hz, which arises in
(this is merely an assumption) these currents various locations across all Europe at irregular times.
are radiated as magnetic fields by the ground- Typical characteristics: phases of activity and intervals
ed Petersen Coil (used for ground/earth leak- changing regularly.
age compensation).

In addition to these signals, previous consid-


ered indeterminate, we must note the increas-
ing level of (mainly daytime-only) ‘pollution’
coming from (presumably) commercial and
communal installations such as inverters,
frequency changers and switch-mode power
supplies. With a little patience it is also fea-
sible to prove the presence of the fascinating Extremely powerful 16 Hz bursts, concentrated at
so-called Schumann Resonances [11] in the particular locations and even audible direct as a deep
region around 7.5 Hz along with the 16 2/3 hum in audio amplifiers.
Hz (50 Hz ÷ 3) ‘signature’ of traction current
used by electric trains, which makes an excel-
lent marker signal for testing and calibrating
the receiver (in places where traction current
uses this frequency). Another conceivable ap-
plication (somewhat frivolous in comparison)
for the receiver is as a highly sensitive detec-
tor for (exclusively) moving metallic objects.
Passing automobiles, for example, can be de-
tected at distances of up to around 20 meters
or 60 feet. Sounding like whistling when played back at high
speed, this sample has reappeared daily for several
hours at the author’s place of residence over the
The following shots show examples of some
years.
varied and interesting ‘signal harvests’:

23
www.elektor-magazine.com | October 2014 | 13

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Operation
Operation of the software recorder in the Win-
Figure 8.
dows-style window (Figure 9) is virtually self-ex-
Power section and filter/
planatory. The test results are shown in three
amplifier should be placed
windows on the left-hand side.
as far apart as possible from
one another. Inductance L4
is fitted in between them Time signal
(here on the underside of An iteration takes five seconds. After the program
the PCB). starts a signal is always visible here, even if it is
not being recorded—and after recording stops.
Software installation
To get a Processing program to run on your com- FFT vs. Time
puter, you need to download the necessary soft- Every x seconds (x depending on the value set
ware from the Internet onto your machine. when downsampling) a new line is plotted—even
Go to the Processing website [7] and follow the if no recoding is being made—and after record-
instructions given there. The data downloaded ing stops.
can go into any folder you choose on the hard
disk. Within this data is also a file with the name Supervisory signal
processing.exe. Run this program if you want to After each iteration of 5 seconds, the highest
write Processing software of your own. Numerous amplitude of this time segment is indicated in
impressive sample programs not only showcase the upper window.
the powerful capability of this language but also
indicate how you can make the best use of it. The parameters for measurement and display
The Recorder program written in Processing can are set on the right-hand side of the recorder:
be downloaded from the Elektor website [8] into
any folder of your choice. Recording time
Length of the recording.
Important: The Processing program must be
located in a sub-folder bearing the same name Downsampling
as the program itself—but without the ‘.pde’ suf- Zoom in the Y direction in order to see the lower
fix. Also all resources required by the program frequencies better. Relates only to the FFT dis-
(such as .wav files or associated graphics) must played and not to the recording.
be kept in this sub-folder. After double-clicking
on the recorder file (Recorder_.....pde) the Pro- FFT brightness
cessing editor window opens automatically and Renders the FFT displayed brighter or darker.
the program code is implemented. Relates only to the FFT displayed and not to the
In the following line you need to replace ‘COM3’ recording.
and enter the COM interface of the PC allocated
by Arduino (see Device Manager in Windows): FFT scrolling
Pages forwards and backwards through the
serport = new Serial(this, “COM3”, 115200); analysis data displayed. Valid only for the data
recorded during the current recording phase still
Then save the program code with File Ž Save. held in RAM. FFT data is not stored on the hard
After a (single) click on the arrow at top-left in disk.
the Editor window, the program begins. The Editor
window with the source code remains during this Mouse position
process on the screen (in the background). Unfor- Mouse position coordinates and number of but-
tunately (and not for want of searching count- tons clicked. Very important if you wish to work
less different sources) I have not managed to on the program yourself.
find a working .exe file for the program. Further
information about Processing can be found in the Recording
Editor itself (Help Ž Reference) and on countless Left-hand button
other Internet pages. Normal method of starting a recording of a dura-

24
14 | October 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


ELF Receiver

tion enter above, automatic saving at the end of


the set time and regular saving intermediately.
Show bright red during recording.
Note that the names of files saved automatically
contain the start time and the intended stop time
(for example 18:20, if the recording began at
12:20 and was set to record for six hours).
If the recording is cancelled ahead of time, you
will find the previously saved data under file name
planned at the outset (2014_07_02_1220_1820).
The file can nevertheless contain just nulls rather
than data from a particular point in the record-
ing, according to the moment of premature can-
cellation. This is because in this programming
language it is possible to save only complete
Arrays and not, as is otherwise normal, only the
section occupied with data. For this reason files
always retain their full size, even if cancelled case, the stop time specified in the file name is Figure 9.
prematurely. the clock time valid at the actual time of cancella- Graphical interface of the
tion. Pressing this button produces an additional recorder software.
Center button file afterwards.
For intentional buffering. This has the same valid-
ity for the filename as with automatic saving. Data output window
Pressing this button makes it possible to observe at lower right-hand edge of screen:
the data recorded up to the current time in an After starting, the time remaining until the time
analyzer. when the recording will end is displayed here
automatically, based on the record duration set.
Right-hand button At the very bottom is the file name, which is also
This button cancels the recording and saves the retained during buffering.
data recorded so far to disk. Note that in this (140035)

Web Links
[1] Online ELF blog: www.vlf.it
[2] https://en.wikipedia.org/wiki/Sallen%E2%80%93Key_topology
[3] Coiled wire: http://www.jameco.com/1/1/379-30pe-awg-plain-enamel-magnet-wire-1-4-lb-825-ft.html [USA],
http://www.scientificwire.com/acatalog/Solderable_Enamelled_Copper_Wire.html Ref: SX0250s-D200 [UK].
Alternatively just look on eBay.
[4] Input transformer: http://www.jensen-transformers.com/ln_in.html
[5] http://blackboard.serverpool.org/
[6] www.elektor-labs.com/project/arduino-16-bit-low-frequency-datalogger-130485-i-140035-i.13703.html
[7] http://processing.org/
[8] www.elektor-magazine.com/140035
[9] https://groups.yahoo.com/neo/groups/VLF_Group/info
[10] http://naturalradiolab.com/
[11] http://en.wikipedia.org/wiki/Schumann_resonances
[12] http://en.wikipedia.org/wiki/Processing_(programming_language)
[13] www.elektor-magazine.com/130485

25
www.elektor-magazine.com | October 2014 | 15

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

16-bit Data Logger


An ADC module for Arduino,
Elektor Linux Boards and more
By Jens Nickel To make accurate voltages
(Elektor Germany)
measurements you need an A/D
converter (ADC) chip which has
good resolution. The folks at
Elektor Labs have developed a
board containing a four-channel
16-bit ADC. It’s no coincidence
the board uses a Gnublin/
EEC connector which makes it
compatible with the Elektor’s
Linux board, Xmega Webserver
and the new Extension shield for
Arduino. A universal C library is
included to make integration a
walk in the park.

This project is a good example of where our Hunting for ELF signals
web-based project platform Elektor.Labs [1] has At Elektor.Labs you can read more details of the
provided the spark for new ideas. Kurt Diedrich, original project [2]: The ELF signal picked up by
an author well known to us, has recently been the large wire loop is first amplified, filtered and
busy experimenting with an Arduino Uno to then given a DC offset of 2.5 V so that the signal
expand his knowledge of microcontroller firm- swings between 0 and 5 V and does not go nega-
ware. It didn’t take too much encouragement tive. The Arduino Uno uses an ATmega328 which
to persuade Kurt to share his experiences with already has a built-in A/D converter but with only
a wider audience via Elektor.Labs. One of the 10-bit resolution. Kurt Diedrich did some research
designs he came up with is a data logger where and ended up ordering a small PCB from Ada-
an Arduino Uno measures a signal level and fruit which has on-board an ADS1115 (from TI).
sends it to a PC [2]. Kurt’s previous experience
with PC programming and graphical user inter- This particular A/D converter has four input chan-
face design could now be put to good use: using nels and can measure signals with 16-bit reso-
the programming language called Processing lution [3]. An I2C bus is used for control and to
he designed a Tool that not only represents the pass information between the chip and microcon-
sampled signal but can also performs spectral troller. It wasn’t long before Kurt was studying
analysis. The complete setup is ideally suited the Arduino code examples and software libraries
for processing the reception of low-frequency supplied by Adafruit. The routines he needed to
electromagnetic signals to be discussed in a implement are not complex; after a little tin-
follow up article describing an ELF Receiver kering with the code examples the data logger
(ELF = extremely low frequency). firmware was finished. An endless loop in the

26
40 | September 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


16-Bit Data Logger

Figure 1. 16-bit data capture using an Arduino:


The ADC module connects to the Elektor Extension shield ARDUINO
ADC-BOARD
via the Gnublin/EEC connector and the shield plugs into
K1
the Uno board. K3
flatcable

main program repeatedly calls the function ads.


USB
getLastConversionResults() from the library, K2
K2
which returns the latest measurement value from EEC / GNUBLIN

the ADS1115 . This is then sent over the serial


interface from the Arduino to the PC. There is no ELEKTOR EXTENSION SHIELD
delay or timer control implemented in the firm-
ware, the measurement frequency is only gov-
erned by the A/D converter’s sample rate. New
values are sent at a rate of about 112 Hz which
Kurt was able to deal with in his PC software.

The concept
The prototype worked really well but the fin- USB
ished set up looked a bit untidy with all those
flying leads between the ADC module and Arduino
board. Labs set about making improvements; the 130485 - 12
main decision was to not make the design into a
dedicated ADS1115 Arduino shield but instead
opt for a more flexible approach that would allow
the board to easily interface to a number of dif-
ferent systems [4]. C1
+3V3
47p
R2 ALERT/RDY POWER
100k
The ADS1115 chip should derive its power from D1 D2
R1
the attached controller board and be controlled 4
100k
REF2912 1
via an I2C bus. A good choice for the interface +3V3 AIDBZT R3 IC2
3 1V022
120k R8 R9 R10
would be the 14-way pin header used by the EEC/ 1 5
IC3 2 0V511 OPA377
C4
560R

1V25 560R IC2


1k

Gnublin boards. The ADC module can then be con- 100n 2


3

C3 C2 R4 R5 T1
nected via a length of flatcable to the Elektor-Li-
270k
120k

nux board [5], the Xmega-Webserver board [6] 470n 10u

or the Elektor Extension Shield [7] (Figure 1). 2N7002


Screw clamp terminal blocks have been used K1 IC2
JP1
for connection of the four analog input voltages.
The chip cannot measure any voltage level which
+3V3 JP4
goes negative below 0 V so to measure alternat- C5 I2C Address
1 2
ing voltages it is possible to select an offset of 3 4
K1 IC1 100n +3V3
around 1 V at the first analog input. 5 6
8

AIN0 7 8 K3
VDD

AIN1 4 1 EEC/Gnublin
AIN0 ADDR
Voltages 5
AIN1 ALERT/RDY
2 1 2
6 9 3 4
The ADC board circuit diagram is shown in Fig- 7
AIN2 SDA
10 5 6
K2 AIN3 SCL
ure 2. The Gnublin/EEC connector used by the R6 R7 7 8
GND

AIN2 9 10
board specifies a 3.3 V supply voltage but the ADC
2k2

2k2

AIN3 ADS1115 11 12
3

chip can operate with a supply range between IDGST JP2 JP3 13 14
2.0 and 5.5 V.
+3V3
130485 - 11

Figure 2. Schematic of the data logger ADC card.

27
www.elektor-magazine.com | September | 41

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

VDD

ADS1115 Comparator
Voltage
Reference ALERT/RDY
AIN0
AIN1 ADDR
AIN2 16-Bit 2
MUX PGA IC SCL
AIN3 ADC Interface
SDA

Figure 3. Oscillator

The ADS1115 has a few


GND 130485-13
built-in niceties such as an
integrated comparator.

The data sheet [3] gives details of how the chip diodes on the inputs which provide some degree
can be controlled and configured using I2C com- of protection but the data sheet recommends fit-
mands. It can be configured to measure: ting external zener diodes and series resistors to
give better protection.
• The voltage level on AIN0, AIN1, AIN2
and AIN3 relative to ground (i.e. four ‘sin- Jumper JP1 can be fitted to provide a 1.022-V
gle-ended’ inputs). offset. The voltage level is made up of the 1.25-V
• The voltage level on AIN0 relative to AIN1 reference voltage level produced by IC3 and the
and the voltage level on AIN2 relative to standard op-amp IC2. When the offset is applied
AIN3 (two differential inputs). the input voltage range is ±2.048 V. An AC input
• The voltage level on AIN0 relative to AIN3 signal swinging between the values of around
and from AIN1 relative to AIN3 (two differ- –1 V and +1 V will be translated into a voltage
ential inputs with a common node). at the ADC input AIN0 swinging between 0 to 2 V
with 15-bit resolution. In the software be aware
The chip outputs a digital value in the range that higher input voltages produce lower output
from –32768 to 32767; negative values indicate values (inversion).
a negative differential voltage (negative values
are expressed in twos-complement format). In Another possibility is to add the offset to AIN0 and
single-ended mode the voltage will always be use the tip described above. With the measured
positive so that the output values will be in the voltage applied to AIN1 or AIN3, the correspond-
range 0 to 32767 which corresponds to a 15-bit ing differential mode configured and a full-scale
resolution. Using a workaround suggested by Ton range of ±1.024 V set. This method makes it
Giesberts in our lab and described in more detail possible to measure a voltage in the range from
on the .Labs Website [8] it allows measurement 0 to 2 V with a 16 bit resolution.
of negative-going signals while producing a 16-bit
value: Apply a fixed DC voltage, say 1 V on input Timing
AIN3. Now an input voltage of 0 to 1 V on the The ADC operates using the Delta-Sigma princi-
inputs AIN0 and AIN1 produces a negative out- ple, which gives good resolution and accuracy.
put value when the corresponding differential This method of A-D conversion however is not the
mode is selected. fastest. A rate of up to 860 samples/s is possible.
The sample rate is configurable and has a default
In addition to an internal voltage reference the value of 128 samples/s. Like many other ADCs
ADC also has a built-in programmable amplifier the ADS1115 can work in single-shot or contin-
which allows you to setup the full scale voltage uous mode. In single-shot mode it is necessary
range that the ADC will measure. In our case, with to issue a command to the chip to tell it to mea-
a 3.3 V operating voltage, the ranges ±2.048 V, sure the input voltage. Once the measurement
±1.024 V, ±512 mV and ±256 mV are of interest. is complete and a valid digital value is available
With this board it is important to ensure the the chip will set a bit in one of its internal regis-
measured input voltage does not go above 3.6 V ters. The external microcontroller monitors the
or below –0.3 V. The chip uses integrated ESD state of this bit and reads the new value from an

28
42 | September 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


16-Bit Data Logger

internal register when it becomes available. It can the role of a slave. Using just write operations you
then go on to request a new measurement. In can, for example set up an internal configuration
continuous mode the chip continually measures registers or tell the chip to start a measurement
the input voltage and produces digital values process. In order to read out a digital value we
without the need for any external intervention. need to both write and read over the I2C bus.
In all our programs including the ELF receiver To be precise you need to write twice (which
application we use single-shot mode in a contin- includes the slave address) and then read once.
uous loop. After each new reading (and before The chip’s slave address can be set-up externally
issuing the next sample command) the value is so it allows more than one ADS1115 chip to be
processed in the microcontroller (e.g. to show connected to the same two bus wires (provided
on the display or send over the serial interface). you use different addresses for each chip). The
Using the default sample rate of 128 samples/s slave address is defined by how pin 1 is con-
produces a data rate of about 100 to 120 Hz nected. There are four possible slave addresses
which should be sufficient for the majority of available; pin 1 can be linked to either pin 3, 8,
data logger applications. 9 or 10 using a jumper on the header pins of JP4
to define the address.
The comparator
The Conversion-Ready-Pin (IC1 pin 2) can be The two I2C signals are connected from the
used to indicate when an A-D conversion has chip to pins 5 and 6 of the EEC/Gnublin connec-
been completed. The ADS1115 can also be con- tor. Jumpers JP2 and JP3 allow you to use the
figured to act as a comparator (Figure 3) and on-board pull-up resistors. The beauty of the
in this mode the pin acts as an alert output. I2C bus is that you can safely interface a slave
Now using values stored in the Low Threshold device operating at 3.3 V with a controller such
and High Threshold registers you can allow a as an Arduino Uno running at 5 V.
sort-of hysteresis or apply a voltage compari-
son window to the measured value so that an The software library
alert occurs only if the measured value is outside When it comes to the control software you know
these stored values. that even if you opt for the default settings of
In our module this output is made visible via the ADC you will still need to spend some time
transistor T1 and a yellow LED. In addition this studying its data sheet. Controlling a microcon-
signal is routed to pin 11 of the Gnublin/EEC con- troller’s I2C interface can also sometimes be a
nector K3 where it is available for use by either bit tricky. Don’t worry; we have simple solutions
the Linux- or Xmega-board but has no connection that should get around these potential problems.
on the Elektor extension shield. The technical boss at the Elektor Labs Clemens
Valens has written a C library that avoids the need
I2C to define which registers you need to address in
As we already mentioned communication with the the ADC and instead provides high level func-
ADC occurs over an I2C interface where it plays tions to control the chip. As a bonus he has also

Web Links
[1] www.elektor-labs.com
[2] www.elektor-labs.com/project/arduino-16-bit-low-frequency-datalogger-130485-i-140035-i.13703.html
[3] www.ti.com/lit/ds/symlink/ads1115.pdf
[4] www.elektor-magazine.com/130485
[5] www.elektor-magazine.com/130214
[6] www.elektor-magazine.com/120126
[7] www.elektor-magazine.com/140009
[8] www.elektor-labs.com/contribution/from-the-lab-using-differential-mode.14034.html
[9] www.elektor-magazine.com/120668

29
www.elektor-magazine.com | September | 43

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

As a bonus the functions

ADS1x1x_start_conversion(&my_adc);

and

uint16 Result = ADS1x1x_read(&my_adc);

are available.

my_adc is a structure, defined at the start of the


program (ADS1x1x_config_t my_adc;) which is
filled via the function ADS1x1x_init(…) with the
required configuration parameters. All following
commands will be given a pointer to this config-
uration structure. More structures can be defined
so that the library can allow more chips to be
Figure 4. addressed on the same bus and independently
To test the ADC module and configured.
the Data logger application
connect a wire from the Using the following command, for example
Arduino pin A3 to the ADC
indicates that the slave chip on the bus with
input at AIN0.
its address pin connected to ground will be
addressed. The input AIN0 will be used in sin-
integrated a small I2C software library, it uses gle-ended mode, the measuring range is –2.048 V
a bit-banging technique to generate the I2C sig- to 2.048 V.
nals. This means that they are also applicable to
controllers that don’t have a built-in hardware ADS1x1x_init(&my_adc, ADS1115, ADS1x1x_
I2C interface. The complete implementation can I2C_ADDRESS_ADDR_TO_GND, MUX_SINGLE_0,
effectively be used with any platform for which PGA_2048);
there is a C compiler. The files, together with a
brief description are available to download from The second parameter indicates that an ADS1115
the web page related to this article [4]. chip is addressed, the library is also usable for
the other ADS111x devices.
First off, bind the ads1x1x.c/.h and soft_i2c.c/.h
files to your own software project. Make sure you The Data Logger software
refer to them with an include statement in your To get a good overview of the design it is a worth-
code. In order to get it on your own microcon- while exercise to study the source code of the
troller, it is necessary to implement the following data logger Arduino sketches, which uses the
five functions (which shouldn’t be too difficult): libraries referred to above [4]. In the next issue

void soft_i2c_scl_write(uint8_t value) // write high or low state to the SCL pin

void soft_i2c_sda_write(uint8_t value) // write high or low state to the SDA pin

uint8_t soft_i2c_sda_read(void) // Read the SDA pin state

void soft_i2c_sda_mode(uint8_t value) // configure SDA pin as O/P (value=1) or I/P (value=0)

void soft_i2c_delay(void) // 8 µs delay

Five further functions bind the ADC library (from you will find more demo programs and interesting
Clemens) with the I2C software library, this code applications which make use of the Embedded
can just be dropped 1:1 into the project. Firmware Library [9].

30
44 | September 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Component List
Resistors (0.1W, 0603) IC1 = ADS1115IDGST
R1,R2 = 100kΩ 1% IC2 = OPA377AIDBVT
R3,R4 = 120kΩ 1% IC3 = REF2912AIDBZT
R5 = 270kΩ 1%
R6,R7 = 2.2kΩ 1% Miscellaneous
R8 = 1kΩ 5% K1,K2 = 3-way PCB screw termi-
R9,R10 = 560Ω 1% nal block, 0.2’’ pitch
K3 = 14-pin (2x7) pinheader, 0.1’’
Capacitors (0603) pitch
C1 = 47pF 5%, 50V, C0G/NP0 JP1 = 3-pin pinheader, 0.1’’ pitch,
C2 = 10µF 20%, 6.3V, X5R with jumper
C3 = 470nF 10%, 10V, X5R JP2,JP3 = 2- pin pinheader, 0.1’’
C4,C5 = 100nF, 10% 16V, X7R pitch, with jumper
JP4 = 8-pin (2x4) pinheader, 0.1’’
Semiconductors pitch, with jumper
D1 = LED, yellow, 0805 PCB 130485-1
D2 = LED, green, 0805
T1 = 2N7002 (SMD SOT23)

Our Arduino sketch performs the same software It is probably easiest to upload the sketch using
function as Kurt Diedrich’s original project: An the Arduino bootloader, that way you only need
endless loop repeatedly tells the ADC chip to a USB cable between the Arduino and PC. Once
measure and digitize the voltage at input AIN0 in the firmware has been flashed the measured val-
single-ended and single-shot mode. The measure- ues can be seen on the serial monitor display
ment range extends from –2.048 V to 2.048 V, in the Arduino development environment or via
while in Single-ended mode only 0 to 2048 mV a simple terminal emulator program (data rate
can be measured and with only 15-bit resolu- set to 115,200 Baud and the corresponding COM
tion. The decimal output values (0 to 32767) port selected).
after conversion are sent out as ASCII characters To achieve the highest measurement accuracy
over the serial interface, followed by a <CR> and it is better to power the Arduino from a bench
<LF> character. power supply rather than from a USB port. It
will provide much better common-mode noise
For testing we used an Arduino Uno fitted with performance.
the Elektor extension shield described in the
last issue [7] connected to the ADC board via a Some spooky signals
14-way ribbon cable. The I2C address of the ADC If you like you can now try out the recorder soft-
board is configured as ‘ground’ i.e. the jumper ware that Kurt Diedrich developed for a his ELF
is placed in the first position of JP4 nearest the reception experiments. Now when you turn the
Gnublin/EEC connector. Initially we will not use pot the values are recorded over time in soft-
any offset correction (JP1 jumper fitted nearest ware. You can also switch in the 1022 mV offset
the terminal blocks). and see how the measured values change. Volt-
Now to generate the voltage to measure we con- age levels in the range of approximately –1 V to
nect a flying lead from the Arduino pin A3 (you +1 V can be measured with 15-bit resolution,
can connect it at the shield box header connec- this set up can be put to good use investigating
tor as shown in Figure 4) to the AIN0 input the presence of ELF signals in your location. If
of the ADC board. The voltage on A3 can now this sounds interesting have a look at the ‘ELF
be adjusted by twiddling the pot on the shield; Receiver’ project described in this issue you may
this gives us a rudimentary test set-up to check be in for some surprises!
operation of the ADC board. The voltage at A3 (130485)
can be turned up to 5 V but it’s important that
the input voltage level does not exceed 3.6 V so
before connection ensure that the pot is turned
all the way down so that the voltage is at 0 V
then slowly increase it.

31
www.elektor-magazine.com | September | 45

Personal Download for Petar Crnojevic | copyright Elektor


•Labs

Arduino is a Tool
By Clemens Valens Barring you just woke up from a 10-year long coma you will have heard about
(Elektor.Labs) Arduino. Everybody is talking about Arduino and all & sundry are developing
programs (“sketches”) and extension boards (“shields”) for Arduino. We have
filled scores of pages in Elektor about, or on using Arduino. Here is another one.

to the Arduino
board to make
the serial port
MIDI compatible
(the Data signal
has to be inverted)
and connected it to the
device-under-test (DUT).
This article however is slightly different because We c o u l d h ave d o n e
it is not about an Arduino project but about without the transistor if we
using Arduino as a tool. I use Arduino quite had used a software serial
often because it is so easy to program and use. port on the Arduino, but it would have meant
I sometimes even use it as a calculator because more testing.
it is quicker to write an Arduino program (called
a ‘sketch’) than a PC application. With the tester ready all we had to do was power
up everything, lean back and watch everything
To give you an example, the other day at Elektor. work just fine. This to me shows the real power
Labs we had to test our prototype of the MIDI of Arduino: an easy-to-use multi-purpose tool
Channel Analyzer [1]. Hedwig our secretary had that can help you out in many prototyping and
brought a nice keyboard with MIDI capabilities test situations.
from home, but, for some reason, it wouldn’t allow So, if you are still wondering what all this Arduino
us to test the analyzer properly. We had run into fuzz is about, try to remember this article the
the chicken-and-egg paradox where we needed next time you can’t figure out how to test your
a MIDI analyzer to figure out the MIDI behavior almost-completed-but-not-working yet super-
of this keyboard to test the MIDI analyzer. So duper ultra gadget.
we called Arduino to the rescue. It took me less (140059)
than five minutes to write a sketch that sent a
Note-On and Note-Off message every second on
Web Link
a different, incrementing, MIDI channel. Elektor.
Labs veteran Ton Giesberts added a transistor [1] www.elektor-labs.com/node/3380

32
82 | July & August 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

My First Shield :-)


LEDs, buttons, display and more

In the microcontroller world as elsewhere,


learning by doing is a good approach. The
Arduino Uno, which features especially
low cost and a low entry threshold, has a
significant shortcoming: almost no on-board
peripherals. We have therefore developed
a compact shield that gives starters a text
display, LEDs and pushbuttons to provide a
good basis for their first projects. There are
also two extension connectors for users who
already have a bit of experience. They can
be used to connect relay modules, wireless
modules and many other devices.

By Jens Nickel Like it or not, very low-cost, mass-produced are fed out to two rows of socket headers which
(Elektor Germany) microcontroller boards have changed the electron- provide the basis for the shield concept. If you
ics landscape. If you want to or have to develop equip another PCB with a matching set of pin
a working project or demo that does not need headers, you can plug it directly into the micro-
very much computing power, you can simply controller board. A shield can hold a wide variety
grab an Arduino Uno – and there’s bound to be of peripheral devices, including displays, sensors,
one lying around somewhere, just waiting to be or interfaces such as Bluetooth or WLAN. Thanks
used. Beginners in particular benefit from the to the widespread use of the small Arduino Uno
free Arduino development environment, and all board, there are now hundreds of commercially
you need to download programs is a USB cable. available shields.
If you prefer to program in Basic, you can also
work with Bascom and the boot loader. Complex Getting started
programs in C or C++ are also possible with the Many of our readers are interested in learning
free AVR Studio environment and a small pro- how to work with microcontrollers and program
grammer, such as the AVR ISP mk2. in Bascom and/or C. For them, the Arduino Uno
is a natural choice. To become truly familiar with
Intelligent shields programming a microcontroller, you need to come
There aren’t many peripheral devices on the to grips with the key interfaces of the IC yourself
Arduino Uno; a single LED is all you get from at least once. The best way to do this, of course,
the board designers. You can also use the USB is to work with peripheral devices that use these
interface to access the microcontroller on the interfaces. Unfortunately, there is hardly any
Uno board (an Atmel ATmega328P) over its UART shield available that provides all the necessary
port. However, most of the microcontroller pins peripherals in a small, low-cost package, so we

33
66 | July & August 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Arduino Extension Shield

decided to develop our own shield. It contains a


display module, two user LEDs, two pushbuttons
and a potentiometer (Figure 1). That means you
can get started right away after you plug in the
shield. For larger projects the shield also has a
pair of connectors which allow other extension
boards to be connected over ribbon cables. A
relay board and a wireless module are already
available, for example.

The shield can be ordered from the Elektor Store Figure 1.


[1] as item no. 140009-91. if you are a nov- The shield is shown here on
ice programmer and you want to try out or use an Arduino Uno board, but it
this small board primarily for demo and exam- can also be used with other
ple applications, you actually don’t need to read 5-V Arduino boards.
any further in this article. Elsewhere in this issue
we describe some initial small applications for (see the “Voltages” inset). On our shield we con-
our shield, written in Bascom Basic. They are nected a power indicator LED to the 3.3 V pin,
also excellent for test purposes. For the C users so that you can see whether the Arduino board
(including would-be users) among our readers, is powered up when the shield is plugged in.
we promise that C software will be coming soon, There are also two user LEDs on the shield, which
since we plan to use shield fairly often in future can be driven by Arduino pins IO10 and AD2.
Elektor projects.

Socket headers Table 1. Arduino pins, microcontroller pins and shield functions
The socket headers of the Arduino Uno are dupli-
Arduino Pin ATmega328 Function
cated on the shield. There is an Arduino standard
SCL PC5 EEC-SCL (*)
for the signals available on these headers, which
must be adhered to regardless of the microcon- SDA PC4 EEC-SDA (*)
troller fitted on the Arduino board concerned. IO13/SCK PB5 ISP-SCK
The individual sockets are also called “Arduino IO12/MISO PB4 ISP-MISO
pins”. The Arduino pins and the corresponding IO11/PWM/MOSI PB3 ISP-MOSI
pins of the ATmega328 microcontroller are listed IO10/PWM PB2 LED2
in Table 1.
IO9/PWM PB1 ECC-GPIOB
IO8 PB0 ECC-GPIOA
Due to the display and the buttons, it is not
possible to plug another shield piggy-back onto IO7 PD7 LCD-D7
the Elektor shield. However, all of the Arduino IO6 PD6 LCD-D6
pins remain accessible when the Elektor shield IO5 PD5 LCD-D5
is plugged in, and in most cases their operation IO4 PD4 LCD-D4
is not affected by the connected shield, as you IO3 PD3 LCD-E
can see from the circuit diagram in Figure 2.
IO2 PD2 LCD-RS
Among other things, this applies to the analog
IO1/TX PD1 ECC-TX
inputs AD0 and AD1, the serial interface pins
RX and TX, and the digital IO pins IO8 and IO9. IO0/RX PD0 ECC-RX
Additional I/O pins can be freed up by pulling AD0 PC0 S1
the jumpers (JP1 and JP2) and unplugging the AD1 PC1 S2
display module. AD2 PC2 LED1
AD3 PC3 P1
LEDs, buttons and potentiometer
AD4 PC4 EEC-SDA
Two supply voltages are always generated on
AD5 PC5 EEC-SCL
Arduino boards: 5 V and 3.3 V. They are available
(*) Connected to AD4 and AD5 on the Arduino Uno
on a socket header and can be used by shields

34
www.elektor-magazine.com | July & August 2014 | 67

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

AD2 is actually intended to be used as an ana-


log input, but on the Arduino Uno board it is
100R
RX connected to the microcontroller port pin PC2,

R7

RESET 5
SCK
MISO 1
1k
GPIOA which can easily be configured in software as

R4
a digital output. LED1 is connected to AD2 and
10
2
4
6
8

3
ECC

ICSP
K1

K7
can also be used as a photosensor, as described
1
3
5
7
9

6
4
2
+5V

+5V
in the Microcontroller BootCamp article in this

MOSI
TX
100R
issue. According to the Arduino standard, pin
R6

GPIOB
1k
IO10 must be able to output a PWM signal. This
R5

gives us the option of using LED2 to visualize the


duty factor of that signal.
EA DIPS082

LCD1 Two pushbuttons and a potentiometer are avail-


VDD
VSS

R/W
RS
VL

D0
D1
D2
D3
D4
D5
D6
D7

able for user input. They are connected to the


E
1
2
3
4
5
6
7
8
9
10
11
12
13
14

AD0, AD1 and AD3 inputs. To allow AD0 and


LCD_RS

LCD_E

LCD_D4
LCD_D5
LCD_D6
LCD_D7

K4
SCL 10
SCL AD1 to still be used as analog inputs, we omitted
P2
10k

SDA
+5V

9
SDA
K3

8
8
7
AREF pull-up resistors and debounce circuitry. However,
7 GND
IOREF SCK 6
it’s very easy to connect internal pull-up resis-
3V3

6 RESET 1k IO13
RESET MISO 5
R3
LED3
3V3 +5V

5 IO12
3V3
5V
4
MOSI 4
3
IO11 tors in the ATmega328, both in C and in Bascom.
3 1k IO10
GND GPIOB 2
The potentiometer is connected to analog input
R1

JP1
LED2

2 IO9
GND GPIOA 1
1 IO8
VIN
1k
LED
AD3. If you configure the A/D converter of the
R2

JP2
LED1

ATmega328 with a 5 V reference voltage, which


K6

LCD_D7 8 IO7
LCD_D6 7 IO6 is common practice, the setting range is 1 to
S1

LCD_D5 6
K5

SDA IO5
AD0
1 330R LCD_D4 5 IO4 1023 (10 bits).
R8

2 LCD_E 4
AD1 IO3
LED LCD_RS
14
12
10

3 3 IO2
8
6
4
2

AD2
4 TX 2
EEC

AD3 IO1
K2

Display
S2

5 RX 1
AD4 IO0
140009 - 11

6
13
11
9
7
5
3
1

AD5
The alphanumeric display module from Electronic
+5V

SCL
10k

P1

330R
3V3

Assembly [2] is removable. It provides two rows


R9

of eight characters, which is sufficient for simple


indications. Two buttons are located next to the
display to enable simple menu control. We chose
Figure 2. Circuit diagram of the shield. The Arduino a display module with a 4-bit parallel interface,
signal lines are also available on socket headers on the which means that four lines in addition to the E
shield. and RS signal lines must be routed to the display.
This is a slight disadvantage compared to an SPI
interface, but software support for the parallel
Figure 3. A wide variety of extension modules can be
connected to the two extension connectors. interface is better. For instance, Bascom provides
specific instructions for writing character strings
to the display.
The display controller is of course HD44780 com-
ARDUINO
patible, which allows popular C libraries to be
433-MHz RELAIS used. The address offset for the second line is
40hex [3].

RS485
PORT-
EXPANDER
UART connector
K1 is a fully wired Embedded Communication
Connector (ECC), which has been described in
WIFI
detail in a previous article [4]. In accordance
(PLANNED) T-SENSOR
with the specification, the UART signals TX and
SHIELD
RX as well as two digital I/O lines are available
ECC EEC/
GNUBLIN ADC here, with a logic high level of 5 V. There is also
BLUETOOTH (PLANNED)
(PLANNED)
5 V constantly available on one pin for powering
140009 - 12
connected peripheral devices. In this case the

35
68 | July & August 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Arduino Extension Shield

Component List
Resistors K1 = 10-pin boxheader, 0.1” pitch
R1,R2,R3,R4,R5 = 1kΩ K2 = 14-pin boxheader, 0.1” pitch
R6,R7 = 100Ω K3,K4,K5,K6 = Arduino Shield stacking
R8,R9 = 330Ω header, Adafruit ID 85
P1 = 10kΩ trimpot with adjuster K7 = 6-pin (2x3) pinheader, 0.1” pitch
P2 = 10kΩ trimpot, SMD, Vishay JP1,JP2 = 2-pin pinheader with jumper, 0.1”
TS53YJ103MR10 pitch
LCD1 = LCD 2x8 characters with back-
Semiconductors ground lighting, Electronic Assembly
LED1,LED2 = LED, low-current, red (SMD DIPS082-HNLED
0805) 2 pcs. 7-way precision socket strip for LCD1,
LED3 = LED, low-current, green (SMD 0805) TE Connectivity 1814655-7
PCB # 140009-1 [1]
Miscellaneous or
Assembled board # 140009-91 [1]
S1,S2 = pushbutton

peripheral device is a small module that gives already been developed in the Elektor labs. The
user projects access to various interfaces to the latter allows the Arduino board to transmit and
outside world (see Figure 3). An RS485 module receive data wirelessly at an ISM frequency like
[4] and a wireless communication module have 433 MHz [5].

Advertisement





  
  
  
 
  
  
  
  
 
  



100uH
toroid YOU DESIGN IT – WE MACHINE IT

Professional quality front panels


www.schaeffer-ag.de

♦ ♦
♦♦••••
••••••
••••
From one piece and at a fair price! Simply
 download our free Front Panel Designer at


 www.schaeffer-ag.de, design your front
 panel and order it directly.


36
www.elektor-magazine.com | July & August 2014 | 69

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Voltages
Due to the countless shields now boards and automatically adjust which would make the shield more
available, the layout and pin to the operating voltage of the complicated and more costly.
assignments of the Arduino Uno socket microcontroller. That is why the However, we have not yet rejected
headers have become a sort of quasi- Arduino socket headers always have this plan, and there are already
standard for extension connectors. not only 5 V and 3.3 V supply voltage several prototypes in the labs. We
More and more microcontroller boards, pins, but also an IOREF pin that is decided to design a less complex
even with 32-bit processors, are being connected to the supply rail for the shield without level converters for the
equipped with this interface. However, microcontroller. Microcontroller BootCamp series from
some of these microcontrollers require Burkhard Kainka and relatively small
an operating voltage of 3.3 V instead We originally planned to develop projects. It is nevertheless possible
of 5 V as on the Arduino Uno board, a shield suitable for all types to connect 3.3 V peripheral devices
and their inputs and outputs are of microcontroller boards, and to the partially wired EEC connector,
therefore compatible with 3.3 V signal furthermore equipped with ECC and and the shield can even be used on a
levels. EEC extension connectors compatible 3.3 V microcontroller board with some
with both 5 V and 3.3 V peripheral restrictions.
Ideally, a shield can be plugged onto devices. That would of course compel
both 5-V and 3.3-V microcontroller the use of several level converters,

All signal pins of the ECC (TX, RX, GPIOA and a master device operating at 5 V, such as the
GPIOB) are connected to the corresponding Ardu- ATmega328 in this case, can easily be connected
ino pins through resistors, based on a suggestion to a slave device operating at 3.3 V, such as a
from Burkhard Kainka. This provides a bit of pro- Gnublin module. Both lines are held at the high
tection in the development environment, so that level by pull-up resistors, which in this case are
the Uno microcontroller will not die immediately located on the extension module, and pulled to
if something a bit higher than 5 V is inadvertently the active low level by the master or the slave.
connected to a pin. Resistors R8 and R9 attenuate reflections on rel-
atively long lines and provide some protection
EEC/Gnublin against noise pulses.
Extension modules compliant with the Gnublin/ The Gnublin modules available in the Elektor Shop
EEC standard can be connected to K2, which is include a board with eight relays, a port extender
configured as an Embedded Extension Connector with sixteen I/O lines, a temperature sensor and
(EEC). This connector is not fully wired because other devices [6].
the standard specifies a 3.3 V level and we omit-
ted a level converter to keep the cost down (see Programming
the “Voltages” inset). Most of the Gnublin mod- The Elektor shield provides everything you need
ules developed by the company Embedded Proj- for experimenting with or learning about the
ects, which are also available in the Elektor Shop, essential function of the ATmega microcontrol-
are controlled using only the I²C lines SDA and ler or another 5 V microcontroller on some other
SCL. One of the advantages of the I²C bus is that Arduino board: digital outputs and inputs, analog
inputs, a parallel interface (four bits), a serial
UART interface and I²C. The only thing that’s
Web Links missing is SPI. The pins for this are fed out to
[1] www.elektor-magazine.com/140009 connector K7, a 2x3 pin header. You can use
this connector to program the ATmega328P on
[2] www.lcd-module.de/eng/pdf/doma/dips082e.pdf
the Arduino Uno board, with the aid of a simple
[3] www.datasheetcatalog.com/datasheets_pdf/S/T/7/0/ST7066.shtml programmer such as the AVR ISP mk2. That will
[4] Elektor March 2014, www.elektor-magazine.com/130155 overwrite the Arduino boot loader, but it can be
[5] Elektor May 2014, www.elektor-magazine.com/130023 downloaded again using the Arduino IDE.
(140009-I)
[6] Elektor Gnublin series http://www.elektor.com/development/gnublin

37
70 | July & August 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Lathe Tachometer
Feat. Arduino Micro & OLED

By Andre Jordaan Here’s a non-invasive, all electronic add-on


(Switzerland)
to display the running speed (rpm) of your
lathe or milling machine, be it CNC or vintage. It’s state of
the art—witness the use of an Arduino Micro board and a .96 inch OLED
display for instantaneous readout. The little instrument also has a clock displaying
the equipment running time.

Attention Bridgeport lathe and milling machine Without even scratching the surface of elemen-
users; get in touch with an electronics geek and tary metalworking and finishing, electronicz peo-
have him build this circuit for you. ple should know that the turning speed is crucial
Attention Arduino users: build this circuit for a for anything that cuts, drills, mills, finishes or
nearby Bridgeport lathe owner and get access polishes metal, wood, glass, and recently, hard
to his prize machinery. plastics, Teflon® and rubber too. In the case
of a round steel bar being milled to end size,
In this project a reflective IRED / phototransistor the turning speed used to do the first couple of
device is used as a sensor to produce a retrofit rough passes using toolbit ‘A’ at angle x may
readout of the number of revolutions of a spin- differ considerably from that applied much later
dle (or “shaft”) on a lathe, a milling machine or for an ultra-smooth surface finish using toolbit
a similar piece of equipment in the metalwork- ‘B’ at angle y. In both cases, the shaft speeds
ing toolshop. have to be set and verified by the operator using

38
14 | June 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Lathe Tachometer

whatever gears or reduction drives are available black adhesive tape or similar is secured around
on the machine. the lathe’s shaft, leaving a narrow gap (of about
To the metalworker, the turning speed his prized 3 mm). Whenever the light emitted by the LED
machine is running at equals the supply volts and reflects off the shaft at the position of the gap,
amps to the electronics engineer. Get the turning it illuminates the internal phototransistor, caus-
speed (≡voltage) wrong and you risk destroying ing the SENS+ line to drop logic Low, and High
your precious stock material (≡64-bit ARM MPU), again when the LED light is not reflected. Hence
object being created (≡Linux dev system) and/ the speed of the rising edges of SENS+ signal
or $50K Bridgeport lathe (≡128-bit LeCroy logic indicates the shaft speed. Note that due to reduc-
analyzer). ≡You don’t want that to happen. tion gears being present in the lathe or milling
Where we write spindle or shaft in the remainder machine the shaft speed is not the motor speed.
of this article of course we mean chuck, 3-claw The Arduino Micro can be reset to force it to start
Figure 1. Schematic of
head, 4-claw head, boring head, end mill, polish executing its firmware from scratch by press-
the precision rev counter
pad, drill, tap, etcetera, since all of these tools are ing S1.
for CNC lathes and milling
fitted eventually to the powered shaft or spindle machines. All measurement
of the lathe or milling machine. Finally, the function of LED2 on Arduino Micro and control functions are
line D7 is free to assign by the programmer—like handled by an Arduino Micro
How it works over rev or call keith [4]. plug-on board.
As with most applications of embedded technol-
ogy the schematic in Figure 1 does not reveal
a lot about the workings or aim of the circuit. In
IC1
fact, you could be looking at NASA’s latest alliga- D1 78L05Z +5V
K1.1
tor counter for use at Cape Canaveral. One of the
reasons for the happy scarcity of components in 1N4148 R1
BT1
the schematic is the use of an Arduino Micro board

390R
C2 C1
9V
in position MOD(ule)1, resulting in all manner of
100n 100n LED1
things being controlled and decided by software
rather than discrete parts. The Arduino Micro is K1.2
first programmed with the project firmware of
+5V
course via its micro USB connector.
+5V R2

The unregulated supply voltage from a 9-V 6LR22


10k

MOD1 +5V
alkaline battery (or a 7 V to 9 V power adapter)
R3 R4
enters the circuit on K1, and gets reduced to 1 1
100R

S1 MOSI SCK
22k

5 volts by stabilizer IC1. LED1 acts as a Power K2 2


SS MISO
2

On indicator. LED+
1
RESET
3
TX VIN
3
2 4 ICSP 4
The Adafruit OLED (organic light emitting diode) LED– RX GND
3 5 5
SENS+ RST RST
display module [1] is connected straight onto 4 C3 6 6
SENS– GND +5V
8-pin connector SV1. The OLED module with its 7
D2 NC
7
10n
monochrome, 128 x 64 graphic display gets its SENSOR 8
D3 NC
8
SV1 9 9
5-volts supply voltage from the same regulator D4 A5
8 10 10
D5 A4
as the Arduino Micro. Other OLED modules may 7 11 11
+5V D6 A3
be used but be sure you match their pinout to 6 12
D7 A2
12
5 OLED_CS 13 13
the board. D8 A1
4 OLED_RESET 14 14
The only input device to the circuit, a reflective D9 ARDUINO A0
3 OLED_DC 15 MICRO 15
D10 REF
IRED / phototransistor (“reflective optical sen- 2 OLED_CLK 16 16
D11 3V3
sor” device) like the one at Yourduino [2], is 1 OLED_MOSI 17
D12 D13
17
R5
connected on K2. The LED inside the device is
OLED
390R

again powered from the +5 volts rail via R3. It


is on as long as the 5-V supply voltage is pres-
LED2
ent. The phototransistor’s SENS+ pin is pulled to
+5 volts by R4, and the signal fed to the INT/D3 130470 - 11

line of the Arduino Micro board. A piece of matt

39
www.elektor-magazine.com | June 2014 | 15

Personal Download for Petar Crnojevic | copyright Elektor


r p c bs
Component List to

er
.e l e k
K1.2 K1.1

v i c e.c
D1
Resistors

ww
R4 K2 R1,R5 = 390Ω 5%, 0.25W
Module 1 R3
om
R2 = 10kΩ 5%, 0.25W w
R2 R3 = 100Ω 5%, 0.25W
MOSI SCK C2
IC1
SS MISO
C1
R4 = 22kΩ 5%, 0.25W
TX VIN
RX GND
RST RST Capacitors
C3
GND +5V C1,C2 = 100nF 10%, 100V, 5mm pitch
D2 Arduino C3 = 10nF 10%, 100V, 5mm pitch
D3 Micro S1
D4 A5
D5 A4 Semiconductors
D6 A3 IC1 = 78L05Z
R5
D7 A2 LED1 = LED, yellow, 3mm
D8 A1 LED2 = LED, 3mm, color t.b.d., optional, see text
D9 A0
D10 AREF
D11 3.3V Miscellaneous
D12 D13 MOD1 = Arduino Micro, Farnell/Newark # 2285194
S1 = pushbutton, PCB mount, 6x6x9.5mm
SV1
SV1 = 8-way pinheader receptacle
8 1LED2 K2 = 4-way pinheader receptacle
R1 LED1 K1 = 9V battery connector clip + wires
Reflective Optical Sensor, like TCRT5000
Monochrome 0.96” 128x64 OLED graphic display, Adafruit #
Figure 2. Printed circuit board layout
326 (UG-2864HSWEG01)
designed by Elektor Labs for the project. 34-pin DIP socket for Arduino Micro (DIY from SIL pinheader
receptacles)
PCB # 130470-1

Software
Listing 1. Excerpt from Firmware.ino
The program “Firmware.ino” is recommended
//to be done when when sensor is interrupted: educational reading if you want to understand
void interrupt_rpm_time() all the ins and outs of the control program, and
{ how it got developed and tweaked. The program
// current_interrupt_time = micros();
is richly commended by the author.
// if (micros() - previous_interrupt_time > (1/fMax))
{
Arduino users will know how to transfer the file
current_interrupt_time = (micros() - previous_interrupt_time);
to their Arduino Micro board, starting from file
previous_interrupt_time = micros();
130470-1.zip, which can be downloaded free of
// Serial.print("+");
charge at [3].
// Serial.println(current_interrupt_time);
// digitalWrite(ledPin, HIGH);
} The Arduino program waits for a rising edge at
} its INT1 input and uses five rising edges to com-
pute the average time between them. Using some
math the rpm (revolutions per minute) is calcu-
void calc_run_Time() lated and sent to the OLED display.
{ A snippet of the program code is printed in List-
//calculating running time ing 1. Here we see how the interrupt produced
unsigned long elapsed; by the sensor gets handled, and the Tachometer’s
unsigned long over; internal clock is ticking to display the “up” time.
elapsed=millis();
h=int(elapsed/3600000); Build it, use it
over=elapsed%3600000; The printed circuit board designed by Elektor Labs
m=int(over/60000); has through-hole parts only and its component
over=over%60000;
overlay is given in Figure 2. Let the electronics
s=int(over/1000);
people handle the programming, board stuffing,
ms=over%1000;
soldering and wiring, and the mech people do
}
the mounting of the board in a case, and the

40
16 | June 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Lathe Tachometer

Figure 3. The Arduino Micro board secured on to the Figure 4. The Lathe Tacho board has boards fitted at
solder side of the tachometer board (early prototype). either side: an Arduino Micro at the solder side, and
a .96” OLED display at the front. Note the use of SIL
pin strip receptacles to ensure the correct mounting
distance.

mounting of the reflective sensor close to the


powered shaft of their lathe or milling machine.
If you are a mechatronics fan you do both jobs
with ease, in the proper sequence.

A slotted optocoupler and a vane fitted at a suit-


able place on the machine shaft may also be
suitable but the assembly is more intricate to
mount—if not invasive. If your machine shaft is
not reflective, stick a small piece of paper on it Figure 5. The Lathe Tachometer startup screens. The
to do the light reflection. OLED readout should blend in beautifully with all manner
of tech info and lights that can be seen in a 21st century
The Arduino Micro is plugged on to the rear (sol- metalworker’s toolshop.
der) side of the Tachometer board (Figure 3);
the OLED unit, on to the front (component) side
(Figure 4). should also be easy to add more channels and
other controls like relays etc. One wish of the
After switching on, the Arduino Micro initializes, author is send the count pulse on to Mach 3—the
then displays the Elektor logo and “Elector Elec- control software for his CNC machine.
tronics” (sic), then “Tachometer by A. Jordaan” (130470)
and the firmware version number (Figures 5a;
5b). Next, the current rpm value is displayed,
and the ‘up’ time of the tachometer (so you can
bill your customers and come across serious).

Over to you
The project being open in terms of hardware and Web Links
software, there should be nothing in your way to
[1] OLED display: www.adafruit.com/product/326
do custom adaptations like getting that k right. It
will be insightful for sure. The hardware for exam- [2] Reflective Infrared Sensor:
ple may be adapted to support different types http://yourduino.com/sunshop2/index.php?l=product_detail&p=217
of sensor types like Hall effect. Other possible [3] Arduino Micro firmware: www.elektor-magazine.com/130470
applications include a step counter, a rev counter [4] Keith Fenner’s Turn Wright Machine Works on Youtube:
for model planes, a PWM percentage meter, or a www.youtube.com/user/KEF791
simple event driven animation on the display. It

41
www.elektor-magazine.com | June 2014 | 17

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

3D Pad:
Touchless Gesture
Control interface
point to make the point

By Jean-Noël Lefebvre (France)

You can easily produce a Touchless


Gesture Control interface that’s capa-
ble of reliably providing 3-dimensional
co-ordinates (X, Y, and Z axes). This
simple, experimental device, designed
in collaboration with the Elektor Labs
team, consists of a sandwich made up
of a PCB called an electrode plane, an
Arduino Uno, and a shield, with control
software.

Be a part of the new revolution in person/machine Detection principle


interfaces, which began a long time ago with… How about ‘projecting’ capacitive detection?
punched cards, followed by keyboards, screens, To detect the proximity of the human body (e.g.
joysticks, mice… Today, touch screens are every- the hand or finger), we are going to be making
where, with so-called ‘gesture’ control, but using use of a technique known as projected capacitive
finger contact (to zoom, unlock, etc.) The new [3]. This is the principle of virtually all the touch
step that Elektor is inviting you to take now is screens on modern phones and tablets―except
touchless interaction, using gestures in the air in that here we are going to be detecting gestures
three dimensions. This isn’t science-fiction―this in the air, relatively far from the detector surface
article is here to prove to you that it’s even … at (10 cm max.) The principle is simple: normally,
your very fingertips. in our circuits, we expect a capacitor to present

42
8 | May 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Touchless Gesture Control

the least possible leakage of the electrostatic field


Specifications
outside its plates. Well, for our proximity detec-
• Touchless 3D gesture detection
tor, it’s just the opposite. We need a capacitor
• Projected capacitance via a plan of four electrodes, Z = 4 inches/ 10 cm
that’s as open as possible, built using copper
• Arduino shield and sketch
tracks (which we’ll be calling electrodes) on an
• Creative Commons license
epoxy panel, so as to obtain maximum “hand
effect” (Figure 1a).

An oscillator under the influence?


The capacitor formed by our electrodes is part Figure 1a.
of a logic-gate oscillator (Figure 1b) whose fre- The first step in
understanding this circuit
quency is influenced by the proximity of a hand
is to imagine the four
or finger when it enters the electrostatic field.
electrodes as capacitors:
This intruder in fact forms a third electrode which in the center, the common
is going to cut the field lines and divert the elec- electrode, and around it the
ON TOP SIDE
trical charges. One of the electrodes, connected ON BOTTOM SIDE 130508 - 13
4 spatialization electrodes
to an inverter output, at low impedance, is called (top, bottom, left, right)
emitting. The other, connected to the junction
between the resistor R and the inverter input
is called receiving; this is at high impedance
(depending on the value of R). Result: the closer
Z
the hand approaches the electrodes, the greater
the extent to which the capacitance between the
electrode diminishes, and the more the oscillator
frequency increases.
When the hand is 10 cm from the electrodes, the
1
oscillator frequency only varies very slightly―a receiver emitting
electrode electrode
few hundred ppm at the very most (100 ppm (top) (center) Figure 1b.
= 0.01%!) Now with this sort of oscillator, the 1 By diverting part of the
frequency is largely determined by other factors capacitive field projected
R by the electrodes, the
too – in particular, the temperature and supply
hand upsets the oscillator
voltage. So the main challenge in our circuit is to 130505 - 16
frequency.
distinguish the very slight variations in the oscil-
lation frequency caused by the hand from those
resulting from the other influencing factors. One What’s it used for?
part of this task is entrusted to the software, so it
There’s a wide range of applications―in the kitchen, for example, to
will also read from two reference electrodes that
adjust the oven or induction ring controls without touching them with
are not (or only slightly) influenced by the hand,
your greasy fingers! In the medical field, when care staff no longer have
but which are subject to all the other factors.
to touch devices, the risk of nosocomial infections will be reduced. In
the huge field of artistic expression, with instruments like the Theremin
“Switching” oscillator
which are played by using gestures in space. In the gaming field, like
As we’re not dealing here with a simple proximity
Fruit Ninja [1] or Despicable Me―Minion [1]. Instead of touching the
detector, but with a system capable of providing
tablet screen, you’ll soon be able to play with movements of your hand
co-ordinates in three dimensions (X, Y, and Z
in the air. I’m counting on you and your imagination and impatient to
axes), our oscillator will be connected to one of
see what you can create around the 3D-Pad!
six receiving electrodes in turn. This device has
four spatialization electrodes: top, bottom, left, Who is it useful to?
right, and two reference electrodes. In the cen- Anyone who wants it, as it’s a very open design. To make it easier to
tre of the electrode plane is the single emitting build and share, and above all to encourage you to express your own
electrode (Figure 1a). To ensure a good response creativity, it is presented in the form of a shield for Arduino. All the
time for the person/machine interface, the six design documentation, diagrams, and software are Open Source under
electrodes will be scanned in turn around 200 a Creative Commons CC BY-NC-SA 4.0 License [2].
times a second, in an operation vaguely akin to

43
www.elektor-magazine.com | May 2014 | 9

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

capacitance between electrodes IC6.D


12
11 ‘1’
& 13
receiver emitting
electrode electrode
(top) (center)

R9 IC6.A
1
3
2 & IC7.C
8
10
Figure 1c.
EN_TOP = ‘1’ 9 &
IC7.D
Detail of the switched ‘1’ 12
11
electrode oscillator circuit 13 &
from Figure 3. Here, the
logic circuit is shown ‘1’
configured with the top
electrode (EN_TOP = 1) 130505 - 15
connected to the oscillator.

multiplexing. The software’s job, at each step the logical AND and NAND operators (IC6, IC7,
in the scanning, is to analyze the oscillator fre- and IC8). You’ll also see that the switching and
quency with each of the electrodes in turn. receiving electrode (EN_X) selection signals come
Figure 1c shows the electrode oscillator in the from the Arduino Uno board (top left). The nom-
state it is at the moment the top receiving elec- inal frequency of our oscillator, in the absence
trode is in circuit. The control signal EN_TOP is of hand influence, is set by R9–R14 at around
high, all the other control signals EN_X are low. 1.6–1.8 MHz.
The three ports IC6A, IC7C, and IC7D now form
just a simple inverter. IC6D is also configured Now that we have an oscillator whose frequency
as an inverter. varies by a few hundred ppm according to the
So this circuit is equivalent to that of the “easily proximity of a hand, all that remains for us to
influenced oscillator” in Figure 1b. With a bit of do is to derive – if possible using a simple solu-
concentration, once you have familiarized your- tion―from that a signal that can be used for a
self with the circuit, you’ll be able to find it in final application. To do this, we need a frequency
the full circuit diagram in Figure 3, by spotting comparator comprising:

external
12 VDC linear 9V 3D Arduino Shield
power supply regulator

préscaler
12V top

phase/frequency
Aalog comparator 9V 5V
Input
buffer
right

center
left

injection
Arduino UNO
SPI reference
DAC SPI VCO
bottom
reference
VCO
USB 5V 9V
serial Port

Figure 2.
130508 - 14
The functions of each of the data to host
three boards.

44
10 | May 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Touchless Gesture Control

IC5 TP1

K6 +5V +9V VIN 78L09F +9V


1
AREF
2
GND
3 SPI_CLK C10 C11 C12
MOD3 13 C9 C8
4
K3 12
100u
6 5 SPI_DATA 100n 100n
TP2 RST 11 100n 100n 16V
5 6 DAC_CS
+3.3V 10 1 16
4 7 MCU_EN_REFA
+5V +5V ARDUINO 9 VCC VDD
3 8 MCU_EN_LEFT MCU_EN_BOT 3 2 EN_BOT
GND 8 AI AO R15 K7
2 MCU_EN_RIGHT 5 4 EN_RIGHT LED1 1
GND BI IC4 BO 470R
1 1 MCU_EN_TOP MCU_EN_REFB 7 6 EN_REFB 2
VIN VIN 7 CI CO
TP3
2 MCU_EN_REFB MCU_EN_TOP 9 10 EN_TOP
6 DI DO
CPF_OUT 6 3 MCU_EN_RIGHT MCU_EN_LEFT 11 4504D 12 EN_LEFT
0 5 EI EO R16 K8
SCPF_CLEAR 5 4 MCU_EN_BOT MCU_EN_REFA 14 15 EN_REFA LED2 1
1 4 FI FO 470R
ANALOG IN

VCO_INH 4 5 ENOSC_SENSE 2
2 3 MODE GND
LED1 3 6 SYNC_SCOPE
3 2 13 8
LED2 2 7
4 TX +9V
1 8
5 RX
K4 K5

14 C15 14 C17 14 C16


IC6 IC7 IC8
K1 7 100n 7 100n 7 100n
IC6.A
1 ELEC_TOP 1
3
2 EN_TOP 2 & IC7.C
8
3 10
IC6.B 9 & +5V
4 ELEC_LEFT 5
4 IC7.D
EN_LEFT 6 & 12
11
IC6.C
13 &
ELEC_CENTER_TL ELEC_REFA 8
10 1 C18
EN_REFA 9 &
IC9
R9 R10 R11 8 100n
C13

* IC6.D
47k

82k

22k

13
11
& 12 IC6, IC8 = HEF4011BT
K2 IC7 = HEF4081BT
IC8.A IC9 = 74HC50
MOD2 1 ELEC_BOT 1
3
130508 - 2 2 EN_BOT 2 & IC7.A
1
3 3
IC8.B 2 & IC9.C
4 ELEC_RIGHT 5
4 IC7.B 7 6
EN_RIGHT 6 & 5 1
4
IC8.C
6 &
IC9.D
ELEC_CENTER_BR ELEC_REFB 8
10 9 10
EN_REFB 9 & 1

R12 R13 R14


C14
IC9.A IC9.E
* IC8.D
47k

82k

22k

OSC_SENSE1 2 3 11 12
1 1
13
11
& 12 IC9.F
OSC_SENSE2 4 5 14 15
1 1

IC9.B

+5V
SYNC_SCOPE
VCO_INH

+5V
TP4
C3
C6
R1
CPF_OUT
100n 10k
100n
TP5 16
14 R3 T1
TP7 VDD C1
VDD 12 3 13
Q1 CIN PC2
1M

SCPF_CLEAR
IC2 11 4 1
OSC_SENSE1 1 Q2 VCOUT PP 2n2
CLK 9 5 2
Q3 INH IC1 PC1 2N7002
6 14 6
Q4 SIGIN CX
74HC24 Q5
5
DEM
10 C2
ENOSC_SENSE 2
RST 4 15 +5V
Q6 ZEN
3 12 HEF4046 7 220p
Q7 R2 CX C7
VSS 11 BT 9
R1 VCOIN
7
VSS 100n
4
OSC_SENSE2
R4
120k
8
R7
TP8 VDD
Figure 3.
Full circuit diagram. Top
10k

R5 R2
IC3 1 DAC_CS
R6 SYNC
+5V
470k

left, the Arduino Uno board


18k

6 3 SPI_DATA
10k DOUT DIN
2 SPI_CLK
C5 C4
R8
DAC8311
SCLK
and below it, the electrode
plane. Everything else is
18k

GND
4u7 100n 5
10V
on the Arduino shield. The
130508 - 11 supply voltage comes from
the Arduino Uno board.

45
www.elektor-magazine.com | May 2014 | 11

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Figure 4.
The scanning of each
electrode generates a
sawtooth whose amplitude
is an indication of the
capacitance detection.

and widely available. Here, it’s not being used as


• a reference oscillator a PLL, but let’s see in the block diagram (Fig-
• a phase/frequency (P/F for short) ure 2) how the 4046’s voltage-controlled oscil-
comparator lator (VCO) and P/F comparator are used. The
• a control and locking program. latter compares the signal from the VCO, which is
going to be our reference oscillator, with the one
Have you already seen that somewhere before? from the electrode oscillator, whose frequency is
Yes, these elements, often used for phase-locked brought down by the prescaler into a range com-
loops (PLLs), are found all together in the 4046, a patible with that of the VCO, i.e. a few hundred
prodigious elderly integrated circuit, well known kHz. Proven over decades, this simple system
allows us to assess the frequency variations in
Figure 5. the oscillator formed by the system of electrodes
These three boards together against the VCO frequency. The conversion of
form the (touchless) gesture the (small) frequency shift into a variation in a
detection device using voltage signal will be easy to use later. The VCO
projected capacitance. This
frequency is adjusted by way of a digital/ana-
principle is the same as for
log converter (DAC) controlled by Arduino via
the ootsidebox.
the SPI port.

Now let’s see how the scanning sequence runs


for each of the electrodes:

• Initial situation: electrode oscillator at rest


(no EN_X signal active), VCO inhibited, no
oscillation. P/F comparator output is zero.
• A set-point value is applied to the VCO such
that its nominal frequency is close to that of
the electrode oscillator. This set-point stays
the same for the rest of the sequence.
• The two oscillators are unblocked and we
let the analog signal coming from the P/F
comparator change for around 300 µs (i.e.
around 30 cycles at 100 kHz) and the scan
is stopped so as to capture the analog value
by launching an acquisition on Arduino; then
the oscillators are blocked again.

The result of this scanning sequence (on one


electrode) at the output of the P/F comparator is

46
12 | May 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Touchless Gesture Control

an analog signal, a sort of sawtooth (Figure 4a), Circuit


whose exact shape and above all maximum ampli- Now you know all about how it works, here are a
tude are a direct function of the frequency dif- few interesting details about the circuit (Figure 3).
ference between the two oscillators. A similar If you change the geometry of the electrodes
sequence will be produced for each of the receiv- by even a tiny amount, or even the technology
ing electrodes, starting the electrode oscillator used to produce the PCB (the influence of stray
with the corresponding EN_X signal and applying capacitances is not negligible), you’ll certainly
to the VCO each time the set-point appropriate have to adjust the values of resistors R9–R14,
for this electrode (Figure 4b). Obviously, it’s the which let you adjust the electrode oscillator fre-
software that determines this set-point. quencies (IC6, IC7, IC8). If you reduce their
In the block diagram (figure 2), the signal called value, the frequency goes up: you need to get
“injection”, coming from the electrode oscillator as close as possible to 100 kHz. Capacitors C13
prior to prescaling, is sent to the VCO to per- and C14 are not fitted.
form what we call “injection locking” [4]: when
an oscillator injects a small amount of energy Buffers IC9A and IC9B (4050) adapt the voltage
into another, it tends to drive the second oscil- level from the oscillator, powered at 9 V, to that
lator when certain conditions are met (in par- of the downstream components, powered at 5 V.
ticular, their nominal frequencies must be fairly The counter IC2 (4024) acts as a prescaler for
close). The driving oscillator tends to impose its the OSC_SENSE1 signal and supplies a lower fre-
own frequency on the other oscillator. The prin- quency (SIGIN) to the P/F comparator IC1. Its
ciple also works on a harmonic, i.e. a multiple Q4 output gives a frequency divided by 16. The
of the fundamental frequency. For our 3D-Pad, signal from its Q3 output (SYNC_SCOPE) is sent
the effect of this is to influence the phase rela- to one input on Arduino. This counter can also
tionship between the two oscillators, and thereby (and will) be reset to zero by the (\ENOSC_SENSE)
the shape of the waveform at the P/F comparator signal from the Arduino microcontroller.
output. The advantage lies in terms of the signal- The VCO and P/F comparator functions are found
to-noise ratio and the robustness against EMC together in the same 4046 IC (IC1); their two
interference – this is crucial, given the extreme end frequencies are determined by R2, R5, and
sensitivity of our system. C2. The electrode oscillator frequency (prior to
So even though it is achieved using logic gates, prescaling) is injected by R4, as per the injection
my detector in fact delivers an analog signal.
Maybe I’m a bit old-fashioned, but seeing this
analog signal directly on the oscilloscope is for I’m not going to go into details about getting started with Arduino. If
me a decided advantage. you need to familiarize yourself with this versatile tool (as I did before
this project), I recommend the following books: Arduino by Günter
When you test this circuit for yourself, once you’ve Spanner and Mastering Microcontrollers with the Help of Arduino by
built it, here’s what one of the electrode signals Clemens Valens [5]. The latter saved me a great deal of time and now
will give: has pride of place within easy reach, just next to my soldering iron.
And not forgetting the other Elektor articles that have already been
• Start by holding your hand far enough away published on the subject.
from the 3D-Pad (at least 6 inches / 15 cm):
the software has stabilized the analog value
at the end of the sequence at 0.7 V.
• Bring your hand closer to the electrodes: the
sawtooth amplitude changes from 0.7 V (@
5 inches / 10 cm) to nearly 5 V @ 0.4 inches
/ 1 cm!

Our 3D-Pad comprises three boards (Figure 5):


the Arduino UNO (in version R3 or higher), the
main 3D-Pad shield board, and lastly the elec-
trode plane. Their different functions are clearly
indicated in the block diagram (Figure 2).

47
www.elektor-magazine.com | May 2014 | 13

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

R1, R3, and C2, with its rapid discharge achieved


by T1, itself driven by an Arduino output (SCPF_
CLEAR). On TP4, we have the usable analog value
(CPF_OUT), both for observing operation on an
oscilloscope and for the Arduino software, after
analog/digital conversion.
For the electrode oscillator, we need 9 V, stabi-
lized by a linear regulator (IC5), itself powered
from a DC voltage of at least 12 V. This passes via
the Arduino, which we’ll be powering from a small
12 V DC power supply (Arduino UNO has provision
Figure 6. locking principle mentioned above. The VCO’s set- for this). IC4 is a step-up level-changer (4504)
The three boards assembled. point voltage comes from IC3, a DAC8311 14-bit which allows the Arduino controller’s 5 V outputs
DAC, itself controlled by Arduino. The resistor net- to control the electrode selection, even though
work R6, R7, and R8 that the DAC output voltage the electrode oscillator is powered at 9 V. The
passes through before reaching the VCO set-point connection between our shield and the Arduino
input makes it possible to avoid the 4046’s loss UNO board is made via K3, K4, K5, and K6.
thresholds―i.e. a minimum voltage below which
the frequency hardly reduces any further, and Construction
Figure 7.
a maximum voltage above which the frequency As all the drawings for the UNO board are acces-
An extract from the code of
the _3Dpad_sensor sketch, does not increase any further, or hardly. sible online, it’s not beyond the bounds of pos-
with (on the right) the data The P/F comparator (IC1) sees at its CIN input sibility for you to build it yourself. But I suggest
sequences corresponding to the signal from the VCO and on its SIGIN input you’d do better to buy a ready-built and tested
the movements detected by the Q4 output from the prescaler. The analog UNO board [6]. The same goes for the two dou-
the four electrodes. voltage is additionally cleaned by the network ble-sided 3D-Pad boards – the track layouts are
available on the Elektor website, but I’d recom-
mend ordering them from the ElektorPCBservice
[7]. A few details deserve special attention, like
capacitors C5 and C12, which must be less than
6 mm high, otherwise you’ll have to fit them
lying down. You’ll need an iron suitable for sol-
dering SMD components, and you’ll have to take
particular care soldering IC3: the DAC8311 is so
small, you need a magnifying glass to spot the
pin 1 identifier.
The electrode plane connectors must be fitted on
the underside of the PCB, so that the screen-print-
ing on this board is on the top once it is plugged
onto the 3D-Pad shield board (Figure 6).
The case must be plastic, not metal. If you’re
lucky enough to own a 3D printer, or have a
Fab-Lab near you, you could have fun designing
an original, futuristic case for it. I used a FIBOX
ABS 125/35 LT case (RS ref. 498-4306) which
has a transparent lid.

Software
The software (sketch) to be downloaded into the
Arduino UNO consists of a file named _3Dpad_sen-
sor.ino and a library ElektorLabs3DPad, to be
installed into the Arduino IDE in the usual way.
This program sends the data to the terminal via

48
14 | May 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Touchless Gesture Control

the USB port, which is used in COM port mode right), rotating movements with turns counting
(fig. 7). The data sequence contains the four and detection of the rotation direction, and push-
electrode measurement values: ing a virtual button (Push).
And for testing, with the _3Dpad_test.ino file
>IN/OUT EL_Gauche EL_Droite loaded instead of _3Dpad_sensor.ino, we have
EL_Haut EL_Bas < commands that allow us to activate the oscilla-
tors continuously, by choosing the electrode to
IN/OUT indicates when the hand is perceived be used. This lets us check the frequencies and
as being (IN) the detection field or not (OUT). adjust the resistors R9–R14 if necessary. There
The program on the UNO board has two main is also a command to make the VCO work with
functions: on the one hand, the scanning and these set-points: 0, Max and ½ (i.e., at the DAC
sequential measurement of the electrodes, on the output, 0 = 0 V, ½ = 2.5 V and Max = 5 V).
other, the regulation, i.e. maintaining the operat- As a bonus, I am offering a very simple but fairly
ing point, taking the two reference electrodes into comprehensive application program, for PC under
account. The principle is the same as for Touch Windows (XP and 7): this displays the 3D co-or-
detectors, e.g. the ones from Atmel. The level is dinates in the form of a cursor whose position on
regulated outside the detection window, which the screen reflects X and Y, while the Z axis is
makes it possible to overcome slow variations represented by the diameter of the cursor; it also
(mainly caused by temperature changes); then displays the words “Air Swipes” when it detects
when the detection is active, this regulation is a sideways sweep of the hand along one of the
usually blocked. In our case, this implies princi- four axes, or the word “Push” when you make
pally that the VCO set-points for each electrode the movement of pushing a button (Z axis); and
measurement are continuously being corrected lastly, it indicates the rotation direction of the
[8]. I can’t go into a detailed description of the hand or finger it detects and the number of turns
software here – it would take a whole article at (very handy for carrying out settings).
least as long again as this one. However, here It will be easy for you to draw inspiration from
are the successive states of the 3D-Pad: this program in Visual Basic 6 for your own
applications.
Self-calibration: (when first brought into ser-
vice or on command via a serial link) the sys- Set-up
tem seeks the operating point for each electrode, Your Arduino UNO board is operational and you
then memorizes the set-points into EEPROM on have installed the software into the Arduino IDE.
the Arduino. You’ll need a voltmeter, an oscilloscope, and a
frequency meter (the latter is unnecessary if you
Setup: each time it is powered up, or on com- can measure frequencies with the ’scope). Once
mand via a serial link, the system quickly (less the components have been correctly soldered,
than one second) seeks the operating point, start- I recommend the usual checks: orientation of
ing from the set-points read from the EEPROM. the integrated circuits and polarized components,
There are also automatic configuration conditions, examination of the soldering using a magnifier
e.g. in the event of saturation of the electrodes. (especially for the DAC IC3).

Run: the normal operating state, which always The tension mounts: Plug together all the
follows on from a successful configuration. boards to form the stack of PCBs (Figure 6)
then plug the 12 V DC supply into the Arduino
The software’s other tasks are: UNO external power jack. It’s a good idea to
check the power rail voltages: 12 V on K3-1, 9 V
Interpolating the co-ordinates: from the mea- on TP1, and 5 V on TP2.
surement values of the top, bottom, left and
right electrodes, it calculates 3D co-ordinates: All OK? Then upload and run _3Dpad_test.ino.
X, Y, and Z. Open the connection with the terminal set to
115,200 baud; a menu of the commands avail-
Gesture recognition: it recognizes swipes in all able appears.
four directions (upwards, downwards, left, and Let’s check the oscillators are working:

49
www.elektor-magazine.com | May 2014 | 15

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

VCO: enter the command to activate the VCO via the serial link, the corresponding command
oscillator with a set-point ½: you should see (e.g. “T” = top electrode, or “B” = bottom one)
2.5 V on TP8 and a nice square wave on TP5 at and check the oscillation signal on TP6. The fre-
a frequency of 100–110 kHz (depending on com- quency should likewise be close to 100–110 kHz.
ponent tolerances). The other commands are documented in the soft-
ware source code.
Electrodes: make sure you clear everything
away from around the electrode plane. For each If these checks are satisfactory, load the normal
of the six electrodes, use the terminal to send, program _3Dpad_sensor.ino in place of the test

Component List
3D-Pad Arduino shield

Resistors
SMD 0805, 0.125 W)
r p c bs
R1, R6, R7 = 10kΩ to

er
.e l e k
R2, R8 = 18kΩ

v i c e.c
R3 = 1MΩ
R9,R12 = 47kΩ

ww
om
R4 = 120kΩ w
R5 = 470kΩ
R10,R13 = 82kΩ
R11,R14 = 22kΩ
R15,R16 = 470Ω

Capacitors
default: SMD 0805
C1 = 2.2nF
C2 = 220pF
C3,C4,C6,C7,C8,C9,C10,C11,C15,C16,C17,C18 = 100nF
C5 = 4.7µF 16V (pitch 2mm)
C12 = 100µF 16V (pitch 3.5mm)
C13, C14 = not fitted

Semiconductors
IC1 = HEF4046BT
IC2 = CD74HC4024M
IC3 = DAC8311 ou AD5641AKSZ
IC4 = CD4504BM
IC5 = 78L09 (SOT-89)
IC6, IC8 = HEF4011BT
IC7 = HEF4081BT
IC9 = CD74HC4050M
T1 = 2N7002

Miscellaneous
K5, K6 = 8-pin pinheader*
K3, K4 = 6-pin pinheader *
K1, K2 = 4-pin pinheader *
K7, K8 = 2-pin pinheader

Electrode Plane

Semiconductors
LED1,LED2 = LED, green, SMD, Kingbright type KPT-2012SGC

Miscellaneous
K1,K2 = 4-pin pinheader*
K3, K4 = 2-pin pinheader*
PCB # 130508-21

* 0.1’’ pitch

50
16 | May 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Touchless Gesture Control

Serial Inventor and Entrepreneur


Jean-Noël Lefebvre learnt electronics with project will shortly be launched on the
his soldering iron in his hand and through Indiegogo crowdfunding website.
reading magazines and specialist books You can participate in his project and
(including Elektor, naturally) The 3D-Pad help him. Follow @ootsidebox on
circuit described here is based on his own Twitter: twitter.com/Ootsidebox or post
patents. A “DIY” enthusiast, he fully supports a LIKE on Facebook: www.facebook.
the concept of HackerSpaces and Fab-Labs, in com/ootsidebox
association with the Makers movement.
en.wikipedia.org/wiki/Hackerspace
Jean-Noël has been devoting his time for a edutechwiki.unige.ch/en/Fab_lab
year now to OOTSIDEBOX, a start-up that is
en.wikipedia.org/wiki/Maker_culture
going to be offering devices like the 3D-PAD,
and also an accessory for Android tablets that www.ootsidebox.com
enables them to be controlled by touchless
gestures, identical to the 3D-Pad system. This www.indiegogo.com

program. A good way of checking the 3D-Pad in scrolling on the terminal [9]. You can launch a
operation consists in connecting a ’scope probe to reconfiguration at any time, either with the com-
TP8 (DAC output) and another to TP4. The sync mand “R” from the terminal, or by saturating the
is taken from TP8. At first switch-on, or follow- electrodes by bring your hand flat within a few
ing the self-calibration command (send “A” from millimeters of the electrode plane.
the terminal), the voltage level on TP8 will fall
gently: this is the search for the set-points for I’ll be there to help you if you need help getting
each electrode. After a few moments, this trace it going or information for a specific application,
should be stabilized (end of self-calibration) and or if you have any suggestions for developing the
your oscilloscope screen should look like the one project. Don’t hesitate to contact me on Twitter
shown in Figure 4b. Bring your hand closer to the [10], I’ll be delighted to answer you personally.
electrode plane: you should see the sawtooth on (130508)
TP4 change and also the measurement values

Web Links
[1] games
Fruit Ninja: http://fruitninja.com/
Despicable Me - Minion Rush: https://play.google.com/
[2] CC BY-NC-SA 4.0 http://creativecommons.org/licenses/by-nc-sa/4.0/
[3] www.embedded.com/design/prototyping-and-development/4008781/
Getting-in-touch-with-capacitance-sensor-algorithms
[4] injection locking: http://en.wikipedia.org/wiki/Injection_locking
[5] www.elektor.com/arduino
[6] assembled, tested UNO board from the Elektor e-shop
www.elektor.com/arduino
[7] www.elektorPCBservice.com
[8] www.rtcmagazine.com/articles/view/101626
[9] video of the sawtooth signal on TP4 http://youtu.be/rYdyR49qFzU
demo video: http://youtu.be/11QGUxXFYq8
[10] @junowhynot + #3DpadElektor: https://twitter.com/junowhynot

51
www.elektor-magazine.com | May 2014 | 17

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

Microcontroller
BootCamp (1)
Arduino and Bascom

By Burkhard Kainka
(Germany)

In the Editorial Office we receive a fair number of


requests from electronics enthusiasts who are looking
for an easy way to get started with microcontrollers. It’s
been a good while since we last ran a large series of articles
on this subject in Elektor, and the associated hardware is vintage,
so it’s high time to run a new series. This series is aimed at our readers
who already have some experience with analog electronics and now want to start
using microcontrollers in their own circuits.

You might ask why you should use a microcon- For comparison: the NE555 timer IC
troller when it’s possible to do so much with First of all there’s the output. When you look
ordinary analog electronics. At first glance, this at the internal block diagram of the NE555 on
looks like a good question. New microcontrollers the data sheet (Figure 1), you can see that it
with more features, higher performance, higher has a push-pull output stage that can actively
clock rates and even more memory are appear- switch high and low. Microcontrollers have exactly
ing all the time, but the first demo program for the same kind of outputs. They are called ports,
every one of them invariably makes a LED blink. where the name “port” can stand for a set of
This leads to the justified criticism that you could outputs or for pins that can be configured either
get the same result by simply taking an NE555 as inputs or as outputs. The circuitry connected
timer IC and adding a couple of resistors and a to the output for a LED blinker application is also
capacitor. That’s absolutely right, and the com- the same: a LED with a series resistor, connected
parison is better than you might think because either to ground (GND) or to the supply voltage
a lot of the elements of an NE555 timer IC can (Vcc). The NE555 also has a second output driven
also be found in a microcontroller. by an open-collector transistor, which can only

52
30 | April 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Microcontroller Bootcamp

switch something to ground. Many microcontrol- the other hand, an analog electronics solution is
lers can also emulate this function. Actually the a better and more economical choice for quite a
only difference is that microcontrollers usually few simple tasks.
have several outputs but the NE555 has only one,
since the push-pull output and the open-collector Anyone with a bit of experience in microcon-
output are not independent. troller development can also mention another
advantage of microcontrollers: once the circuit
Next we have the inputs of the NE555, which is complete, you don’t need to touch the solder-
consist two inputs to a comparator that controls ing iron again. From that point on, all you do is
an internal flip-flop. A typical application for this write and test code. Changes to device functions
is an astable multivibrator, which hobbyists often can be implemented and tested very quickly.
call a blinker circuit. You can put all this together Microcontrollers are general-purpose and versatile
in almost no time. You just plug the numbers computation workhorses. The learning curve is
into a couple of formulas to determine the right worth the effort, since you ultimately save time.
component values, and then the NE555 does Your first exposure to a microcontroller data
exactly what you want. Determining the compo- sheet may put you off, since it can easily amount
nent values for an NE555 circuit and program- to 300 pages or more. Fortunately, there are
ming a microcontroller are actually comparable
tasks. There’s another thing that’s very similar:
both devices (NE555 and microcontroller) have
VCC
a Reset input that you can use to set everything
RESET
back to the starting point. And with both devices 4 8
VCC
the Reset input is usually high in the quiescent
state and must be actively pulled to ground.
5k

DIS-
THRESHOLD 6 INHIBIT/ 7
Figure 2 shows a simple square-wave genera- R
RESET CHARGE
CONTROL 5
tor in the form typically used as an LED blinker. VOLTAGE

The NE555 data sheet also shows several other Q


5k

basic circuits, including a monostable and a pulse- FLIP-


FLOP
TRIGGER 2
width modulator—all of which are typical tasks S
3 OUT
for microcontrollers. If you further consider the
countless NE555 applications you can find some-
NE555
5k

where on the Internet, you certainly have to


agree that in many cases all you need is a 555 1
GND
timer IC and a microcontroller is overkill. For Figure 1.
everything from light curtains to servo controls Block diagram of the NE555.
or processing analog sensor signals, there are
many things that can be done with this IC and
similar devices. And you can be sure that there
are still lots of potential applications that haven’t
been worked out yet.

Reducing development time 4 8


7 RES VCC
The similarities between the NE555 and a micro-
100k

DIS
controller are summarized in Table 1. You could
3
OUT
formulate the result of a fair comparison as fol- 9V 6 NE555
THR
lows: The microcontroller has a bit more of 2 TR
1k

CV GND
everything and is therefore generally the better
5 1
choice for complex tasks. For example, a single LED

microcontroller could probably handle a task that


22u
would take ten NE555s. Above a certain level of
Figure 2.
complexity, the microcontroller solution is also Blinker circuit with the
smaller and cheaper than the analog solution. On NE555

53
www.elektor-magazine.com | April 2014 | 31

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

you don’t entirely understand how it works. The


Table 1. Comparison of NE555 and microcontroller.
main thing is to have a couple of positive expe-
NE555 chip ATmega microcontroller
riences at the beginning, and after that it just
Switching output Port outputs
goes automatically. That’s doubtless the reason
Inputs Port inputs why the first demo task for every microcontroller
Timing control Internal timer is a LED blinker. Here as well we remain true to
by RC networks driven by crystal-controlled clock this tradition, if only to maintain the comparison
Reset input Reset input with the NE555.
Comparator inputs Comparator; analog inputs
Arduino and Bascom
PWM function PWM outputs
Microcontrollers actually come in all sorts and
Analog signal processing Analog to digital converter
sizes. At the start of a series such as this we are
Flip-flop Memory cells faced with the choice of which system to use,
and there are many different options. We spent
a long time talking about which microcontroller,
approaches to the world of microcontrollers that which circuit board (existing or new), and which
do not require you to understand everything right programming language we could specifically rec-
up front. In many programming languages the ommend for beginners. Our discussions led to
first steps are very easy. You just need to have the following proposal: hardware: Arduino Uno;
enough confidence to try something even when software: Bascom.

Arduino has become the most popular system


in the hobby environment. The programs are
developed on a PC using a simple programming
language, and they can be downloaded directly
to the microcontroller over a USB connection.
A large variety of boards and extension boards
(Arduino shields) are also available at amaz-
ingly low prices. The entire system is based on
the open-source concept, so the software and
the hardware are fully documented. The low-
cost Arduino Uno board [1] is a good choice for
Figure 3. our course because it is equipped with a widely
The Arduino Uno board. used microcontroller. The ATmega328 is an AVR
microcontroller made by Atmel. Programming this
device is quick and quite easy. The microcontrol-
Table 2. Arduino Uno at a glance.
ler has enough memory to allow relatively large
Microcontroller ATmega328 programs to be executed later on (see Table 2).
Supply voltage 5V There is a dedicated development environment
USB port 5 V supply and device programming available for the Arduino. A development envi-
External power supply 7–12 V ronment in this context, also called an integrated
development environment (IDE), is a PC pro-
Digital I/O pins 14 (of which 6 can be used for PWM output)
gram that is used to develop programs for a
PWM channels 6
microcontroller. In the development environment,
Analog inputs 6
the microcontroller programs are typed in using
Current per I/O pin 40 mA (max.) an editor and then converted into bytes by the
3.3-V output 50 mA (max.) compiler, after which they are downloaded to the
Flash memory 32 KB (with 0.5 KB occupied by the boot loader) microcontroller.
SRAM 2 KB (ATmega328)
To ensure that the compiler understands what
EEPROM 1 KB (ATmega328)
the microcontroller is supposed to do, you must
Clock speed 16 MHz
adhere to the syntax rules of a particular pro-
Price (for Elektor Members) $39.70 / £24.75 (check [1]) gramming language when you write the pro-

54
32 | April 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Microcontroller Bootcamp

gram. The Arduino IDE uses a simple version of


+5V
the C programming language, which is the lan-
guage used by most professional programmers.
It also has several special commands that make
program development easier. Many users have 100n

become familiar with this programming language 20 7 21


AVCC VCC AREF
and have no trouble working with it. Neverthe- 1
RES
less, for this course we chose the Basic program-
23 14
ming language. There are many reasons for this C0 B0
24 15
C1 B1
choice. One is the Bascom Basic compiler for 25 16
C2 B2
AVR microcontrollers, which is widely used and 26
C3 B3
17
27 18
popular. The learning curve is especially easy, in 28
C4 B4
19
C5 B5
part because Bascom includes many special com-
ATmega328p
mands for sending characters from a microcon- 2
D0 D7
13
3 12
troller to a PC, for showing letters and numbers D1 D6

1k
4 11
D2 D5
on a display, and much more. However, perhaps 5
D3 D4
6

the most important reason for using Bascom is GND X1 X2 GND


that it makes you fit for all AVR controllers. The 8 9 10 22
LED
selected Arduino board (Figure 3) is used here
as a learning platform, but in the end you can 16MHz

use any desired AVR microcontroller on other 22p 22p


Figure 4.
commercially available boards or on your own linker circuit with a
boards. You also don’t have to limit yourself to microcontroller.
ATmega devices. For example, you may be able
to manage with the compact ATtiny13, which a piece of prototyping board. This means that
has only eight pins. if you wish, you can follow the entire course
without the Arduino board. However, it’s more
A special feature of the Arduino board is the USB convenient and easier for beginners to use the
port. In addition to downloading programs to the Arduino Uno board.
microcontroller as described below, you can use Listing 1 shows the Bascom program for the LED
it to send characters back and forth between the blinker. It starts off with two directives for the
PC and the ATmega328. Among other things, compiler, which define what is called the envi-
you can use this to control the microcontroller
remotely from a PC program or to send mea-
surement values captured from sensors by the Listing 1. LED blinker
microcontroller to the PC and display them on '-----------------------------------
the PC. Another thing is that the board can be 'Uno_LED1.BAS
powered over USB if you so wish. All you need
is a USB cable, and you’re ready to go.
'-----------------------------------
$regfile = "m328pdef.dat" 'ATmega328p
Your first program
One option for putting together a blinker circuit $crystal = 16000000 '16 MHz
with an ATmega328 is shown in Figure 4. To '-----------------------------------
make it easier to see what matters here, the cir-
cuit diagram shows the microcontroller without Config Portb = Output
all the peripheral circuitry of the Arduino board.
The LED is already present on the Arduino board, Do
so you don’t have to put anything together. Portb.5 = 1 'LED on
Similar simplified circuit diagrams are also used Waitms 500 '500 ms
for the other example applications described later Portb.5 = 0 'LED off
on. The idea behind this is that you can also try
Waitms 500 '500 ms
out all of these examples using a bare micro-
Loop
controller, for example on a breadboard or on

55
www.elektor-magazine.com | April 2014 | 33

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

ronment. This is necessary because the Bascom Portb.5 = 1


compiler needs to know the target microcontroller Waitms 500
for compiling the program. The Arduino Uno is Portb.5 = 0
equipped with an ATmega328P, so the directive is: Waitms 500

$regfile = “m328pdef.dat” The individual line to the LED is switched to the


“high” voltage level (close to the supply volt-
You also have to tell the compiler what clock age of the microcontroller) by the instruction
speed the microcontroller runs at. The higher Portb.5 = 1. This causes a current to flow through
the clock speed, the faster the microcontroller the LED. The port pin is switched back to the
executes the instructions. This can be important “low” voltage level (close to the ground level) by
when dealing with things that require exact tim- the instruction Portb.5 = 0. There is also a wait
ing. An example is sending characters to the PC instruction to delay program execution. Waitms
at a particular data rate. The board has a 16-MHz 500 is self-explanatory; it causes a time delay
crystal that sets the clock speed of the controller. of 500 ms. All of this is built into a loop struc-
ture. Everything between “Do” and “Loop” will
be repeated indefinitely. The only way to stop
the program is to switch off the supply voltage
or press the Reset button.

Software: the compiler


So far, so good. But how is the program con-
verted into an executable form, and how do you
get it into the microcontroller? The Bascom Basic
compiler was developed by Mark Alberts for the
8051 family and for AVR microcontrollers. First
you have to get a copy of this PC software. It is
available from the website of MSC Electronics
[2]. You can opt for the paid full version or the
free demo version. The demo version is fully
adequate for trying out the software and for get-
ting starting with programming. It is limited to
programs that occupy up to 4 KB (4,096 bytes)
Figure 5. The corresponding directive for the compiler is: after compilation. By comparison, the Arduino
The first program in the has room for up to 32 KB. However, 4 KB is not
Bascom editor. $crystal = 16000000 peanuts; it takes a fair amount of programming
effort to fill it up. Most of the examples in this
Before you get to the actual program, there’s series will be much smaller.
another important configuration issue: the port Installing Bascom is very easy. After you launch
pins of the microcontroller can be used as inputs the program, the first thing you see is an empty
or as outputs. All port pins are initially config- Editor window where you can type in your own
ured as inputs after a restart. Here we need an program. Of course, you can also import an exist-
output, so the corresponding port must be con- ing program into the Editor (see Figure 5). These
figured accordingly: program files (with the suffix .bas) are plain text
files that can also be viewed with Windows Note-
Config Portb = Output pad or another editor program. This is called
“source code” because the compiler uses the con-
This instruction configures all six pins belonging tents of these text files as the source for compila-
to port B as outputs. The program actually only tion. The compiled program is called “hex code”
uses port pin PB5; all of the other pins remain because the bytes are often shown in hexadecimal
unused. Why did we choose PB5 in particular? notation, always with two hex characters in the
Because a yellow LED is already connected to range 0–9 and A–F per byte. Numbers in the form
this pin on the Arduino Uno board. of bits and bytes and the various notations used

56
34 | April 2014 | www.elektor-magazine.com

Personal Download for Petar Crnojevic | copyright Elektor


Microcontroller Bootcamp

for them will be a frequent topic in this series on doesn’t work in practice, and likewise a micro-
microcontroller programming. controller with nothing in its program memory
cannot program itself. However, this is possible if
You can type in the program in Listing 1 yourself a boot loader is already present in memory, and
or download it from the Elektor page. The file the Arduino comes with a built-in boot loader.
UNO_LED1.bas is located in the zip folder [3]. The development environment on the PC also has
Compiling the program is very easy: simply click to be able to download program code using the
Program/Compile, click the corresponding icon Arduino boot loader. Fortunately, Bascom devel-
on the toolbar (a black IC), or press the F7 key. oper Mark Alberts already guessed that some-
If there is any sort of error in the source text, one would want to program an Arduino board in
an error message will be displayed. If there are Bascom at some point in time, so this capabil-
no problems, a pop-up window shows what per- ity is already incorporated. After you configure
centage of the memory is occupied. In this case the right settings, everything is quite easy. Here
it is less than 1%, which is rounded down to 0%. we describe how this works with the demo ver-
What matters is the resulting hex file UNO_LED1. sion, since there is a small difference with the
hex or the binary file UNO_LED1.bin, which are full version.
two different file formats with the same con-
tent. They contain the executable code for the
microcontroller. Now you have to load this code
into the microcontroller’s flash memory. There
are many ways to do this, and for now we only
describe the simplest way. Other options will be
described in subsequent instalments.

The simplest way: use the boot loader


This program must be located in the microcon-
troller’s flash ROM in order to run on the micro-
controller. Flash ROM is a special type of memory,
Figure 6.
similar to EEPROM, in which electrical charges
The settings for the Arduino
ensure that the memory contents are retained
boot loader.
reliably for many decades. Flash ROM can be
rewritten repeatedly (“flash” refers to very fast
writing), so programs stored in flash memory can First you have to install the original Arduino soft-
always be altered at a later date. Special pro- ware available from [4], which includes the USB
gramming devices are available for programming driver for the Arduino Uno board. Then you con-
flash memory. They are connected to specific pins nect the Arduino Uno over a USB cable. The driver
of the microcontroller, and the program bytes are is loaded automatically, after which the Arduino
received from the development environment on Uno should be visible in the Windows Device Man-
the PC via the USB link. ager window. There you can see which COM port
However, this can also be done without a pro- number (e.g. COM2 or COM3) has been assigned
gramming device. When the Arduino board has to the Arduino Uno. If you wish you can change
a USB connection to the PC as mentioned above, the COM port number in Device Manager, but this
the program bytes can be sent to the micro- is usually not necessary. However, you should
controller over the USB link as long as there is note or write down the COM number. If you wish,
a small program running in the microcontroller you can also open the Arduino IDE and try out a
that receives the data and writes it to the micro- couple of sample programs. However, here we
controller’s flash memory. want continue straightaway with Bascom.
This small program is called a boot loader, which
is related to the expression “booting up” for start- In Bascom you can choose from a large variety
ing up a computer. This term originates from the of programming devices and boot loaders under
word “bootstrap” in the saying “pull yourself up the menu item Options/Programmer. The right
by your bootstraps”. Of course, pulling yourself setting is “ARDUINO” (not “Arduino STK500/2”),
out of the mud by tugging on your bootstraps as shown in Figure 6. It’s also important to con-

57
www.elektor-magazine.com | April 2014 | 35

Personal Download for Petar Crnojevic | copyright Elektor


•Projects

program is stuck. Incidentally, ESC also works


with the full version.
Now you’re done, and it’s time for action. As pre-
viously mentioned, press F7 to compile the source
code. Then press F4 to start the programmer.
Alternatively you can click the small green PCB
symbol “Program Chip”; the result is the same.
In any case, a new Programmer window opens.
There the compiled program (UNO_LED1.bin) is
already nicely loaded and displayed in the form
of hexadecimal numbers (Figure 7).

Good job: it works!


After this you can sit back and relax; the rest is
automatic. However, you can also do everything
yourself. If you opt for this, you must be very
careful because there is a function here that can
completely erase the microcontroller memory,
which means that the Arduino boot loader is also
gone. Stay well clear of anything with the word
“erase” in it. The only right option is “Chip/Write
Buffer into Chip”.
Now you will see a long chain of messages in
the programmer window, with the lovely word
“Started” at the end. During the programming
Figure 7. figure the right COM port (in this example COM2), process you can see from the activity of the Tx
The compiled program in and it’s essential to configure the right baud rate and Rx LEDs on the Uno board that a lot of data
the form of hex numbers. (115,200). This is because both parties must traffic is going on. At the end the window closes
agree on the data transmission rate in bits per again.
second (baud). We’ll come back to this subject
later on in the course when we talk about send- The downloaded program starts running imme-
ing messages and measurement data to the PC. diately after the end of programming, and the
If you only go by the Bascom help and the exam- yellow LED blinks. It may be a tiny program,
ples included with Bascom, some of your settings but it’s a big step for you as the programmer. If
will be wrong here because the Arduino Uno is you’re not quite sure about all this, try making
relatively new and the Arduino camp has only some small changes to the program. For example,
recently changed to the highest standard trans- you can change the blinking rate. For really fast
mission rate of 115,200 baud. All in the interest blinking, change Waitms 500 to Waitms 100, or
of fast data transfer and correspondingly super- for very slow blinking change it to Waitms 2000.
fast device programming. Time is scarce in our After editing the code, recompile it and repro-
fast-paced era. gram the microcontroller, and then check the