DIYode September 2017
DIYode September 2017
FREE
ALTRONICS
CATALOGUE
BUNDLED WITH
THIS ISSUE
BUILD
SAM
Issue 003
Sept 2017
AUS: $9.95 inc. GST
ISSN: 2207-8045
03
OUR "SOMEWHAT
9 772207 804002
AUTONOMOUS MACHINE"
MAN'S BEST ROBOTIC FRIEND - LEARN ALL ABOUT USING BUILD A RASPBERRY PI
AN AMAZING CREATION VOLTAGE REGULATORS VIDEO EVENT RECORDER
An interactive, Arduino-powered These handy devices make Trigger recording from an alarm
K9 replica, and it looks amazing. regulating voltage really simple. system, panic button, or web app.
Reinvent your
energy
With clean, reliable solar energy and Tesla Powerwall 2,
Bradford Solar puts you in charge, day and night.
For most of you, this issue would have arrived quite a bit bulkier
than usual. This is because we partnered with Altronics this month,
to include a FREE copy of their 408-page 2017/18 catalogue. All our
Aussie-based subscribers, as well as most copies in retail outlets
across Australia were bundled like this; if you’re reading this issue
digitally, then simply head to altronics.com.au/catalogue where you
can directly download or request a printed copy.
All you need to put it together, are a few tools and the
"This is SAM" project on page 58 of this issue!!
50
91
20
EDUCATION:
■ FUNDAMENTALS
Keeping it Regular 37
■ SECRET CODE
Arrays & Loops 50
■ THE CLASSROOM
30 86
Resistors & How to Use Them 66
■ WHAT THE TECH
MQTT Protocol 88
PROJECTS:
■ T IME-LAPSE SLIDER
With A Touch Screen Interface 20
■ MQTT LIGHT SWITCH
Light Up From Anywhere 40
■ THIS IS SAM.
Somewhat Autonomous Machine 58
■ VIDEO EVENT RECORDER
For Network IP Cameras 72
■ PART 2: ALARMDUINO
More Great Features 91
■ E DITOR'S LETTER
The Next Phase of DIYODE Mag 04
■ NEW & REVIEWED
littleBits & Lulzbot 3D Printers 08
■ MOONSHOTS
Low Voltage Mains 28
■ GOING PRO
3DBRINK Aussie 3D Printers 86
■ THE ADVENTURES OF
66 CIRCUIT MODD 98
Grab it Now:
littleBits
Rule Your Room Kit
There can be a thrill in teaching kids the a USB keyboard or mouse and take control car. It also allows you to tap into your
fundamentals of electronics. But equally, of your computer. Smartphone’s gyro, accelerometer, and
there can be challenges, such as keeping camera to help you create the ultimate
them engaged, ensuring parts are safe to The modules can be plugged into the inventions!
use, and avoiding the need for soldering. We supplied mounting boards or separately.
noticed that Jaycar recently released some 3M adhesive shoes are also supplied, so While the kits may seem a little pricey, they
great looking kits from littleBits, so we took you can mount your circuit on all kinds of do provide quality parts that the kids can
a closer look. surfaces. These littleBits modules are quite connect without letting the smoke out.
small, and colour-coded depending on their There are also the benefits that come with
We checked out the “Rule Your Room Kit” function; for example, pink for input, green being part of the littleBits community, which
and found it is well packed, with a moulded for output, blue for power, and orange for – as littleBits say – makes for endless hours
tray, a servo, a quality Duracell battery, a wire. The magic is in the built-in magnets, of fun! ■
78-page, full-colour invention guide, and a which ensures the Bits can’t be snapped
bag containing two mounting boards, a USB together the wrong way.
cable, and a handful of accessories. There
are also several components they call “Bits”. The invention guide contains instructions Shopping List:
for eight inventions, so it’s ideal to get you
The Bits in the “Rule Your Room Kit” include started. There’s also an app available from littleBits Kits are available
a power module, dimmer, sound trigger, the App Store or Google Play, so you can at Jaycar Electronics:
bargraph, buzzer, servo, and a “Makey access thousands more, and even share www.jaycar.com.au
Makey” Bit. This Makey Makey Bit turns your own creations with the community.
everyday conductive objects – like bananas ► RULE YOUR ROOM KIT
or play dough for example – into triggers to If you’re after a larger kit the “Gizmos & KJ9120 $199
control your circuit; and there are alligator Gadgets Kit” includes many more parts, ► GIZMOS AND GADGETS KIT
clips supplied to help connect to different including a Bluetooth module, to help you KJ9100 $389
materials. The manual even shows you how really take control of your invention – by,
you can use the Makey Makey Bit to act like for example, making a remote controlled
Spotlight on:
LULZBOT
3D PRINTERS
When it comes to 3D printers, the product ranges are virtually THE RANGE
unlimited. But in our experience, the quality across different ranges
can vary immensely. There are two different sized printers in the LulzBot range: the
“baby” (a LulzBot Mini), and the “big kahuna” (a LulzBot TAZ 6).
At DIYODE HQ, we’ve experienced prototyping struggles with many Both printers follow the same Cartesian-style design. The larger TAZ
forms of 3D printers. We’ve had ongoing challenges finding a 6 has options for dual extrusion and other interchangeable heads,
cost-effective printer that would produce on-demand, without any which are not available with the Mini. Of course, the print size
fuss, and without a high failure rate. Until we stepped into LulzBot drastically increases from a fun 152 x 152 x 158mm (2,650cm3), to
territory... a huge 280 x 280 x 250mm (19,600cm3)! Don’t get us wrong - the
Mini is awesome and works brilliantly, but the size of the TAZ 6 is
Our friends at Core Electronics have extensive 3D printing definitely a lot more useful.
experience, so we asked them what 3D printer they would
recommend. Without hesitation, they dropped the brand: LulzBot. FIRST IMPRESSIONS
We’d heard the name, read the reviews, but hadn’t yet used them.
The guys at Core Electronics assured us of their quality, reliability, One thing that was really impressive, was that each machine is
and best of all, their technical support. They are also open- quality controlled before it leaves the factory. This is evidenced
source, so you can even print your own replacement parts and by the model Octopus that is included with the printer, which
improvements if you want to! has actually been printed by your very machine. The steppers
have stepped, the extruder has extruded, and the heat bed has,
We got our hands on a few models, to put them through their paces; well... heated! It’s by far the best way to know that your machine
and here’s what we found. works, which is really important, since there’s no better way to kill
excitement than to find out the equipment doesn’t work!
GETTING STARTED Two great features of the LulzBot units are the self-cleaning and
self-levelling functions. At the start of each print, the printer will go
The set up was impressively fast. The LulzBot Mini comes fully through the automatic levelling process, as well as multiple cleaning
assembled so it, literally, takes a few minutes to pull it out of the passes on the integrated cleaning pad. Historically, our frustrations
box, remove the packing material, and connect it to your computer. with 3D printing and the cause of many failures, was often a result
The TAZ 6 is a much larger unit, but while it comes in a few pieces, of problems with nozzle clogging and bed levelling (despite going
it’s still barely a five-minute job to set up; the instructions are really through calibration processes).
clear, and all required tools are included. There’s no “construction”
really, you’re just bolting the print bed/y-axis on, and plugging We messed about with various settings, from quick and dirty prints
the extruder head in; very basic assembly. Then - as per the Mini - to slow and fine prints. In each case the results were exceptional. Of
connect, switch on, and you’re practically done. course, we also played around with resolution differences so there
are adjustments to the output quality, which you can see in the
While LulzBot is compatible with all sorts of printer software, they photos of our Rocktopus models. At first glance they look the same,
have a pre-configured version of Cura available (Cura LulzBot which is great; but there are minor differences in the resolution of
Edition), which further accelerates the set up procedure. By using the layers, and the finer prints can take double the time, or longer to
the provided version of Cura, there’s no configuration of your printer complete. However this is the nature of 3D printing. It’s a trade-off
required. Simply click on the printer you have, and everything is between the print speed and the quality of the output. Even the
basically ready to go. They even preload the iconic “Rocktopus” “fast” preset seemed to provide better outcomes than many other
model, so you have something to create a great test print too. printers we’ve previously used.
Cura is a great piece of software, and with the preloaded printer PROBLEMS
profiles, we really don’t see too many reasons to use different
software; but the option is there should you have a need. The LulzBot/Cura experience really is one of the easiest and most
robust 3D printing systems we’ve ever used. However, one bug
PRINTING we discovered was with Cura, where during a very long print, the
system locked up. The printer kept printing, but we lost monitoring
Once we ensured there were no bugs in the system, no loose screws and interactivity in Cura. We experienced this about 12 hours into
or anything like that, we set about putting the printers through a 32-hour print so we were a bit nervous, to
their paces. We found simple models, complex models, and some say the least. Online research revealed
fun things to print. This was a deliberate “stress test” of the units. reports from various places, and noted
Just about any 3D printer can produce a tiny, featureless print, with the problem across numerous platforms,
relative success, but we weren’t looking for an “okay” result; we so we’re confident the fault did not lie
wanted the prints to be reliable and the results to be great. After all, with our own Mac. This issue is probably
we’re not just playing around - we’re creating models for use in our one major reason to use the onboard SD/
projects, and prototypes that we’re going to publish - accuracy and untethered printing on the TAZ 6, as it
repeatability is critical for our purposes. would mean we could restart Cura, or the
computer if required, without affecting ››
›› the print at all. This particular print of ours was being performed concentrated on PLA material, which is the most forgiving and
by the Mini, so this wasn’t an option; but that being said, it’s reliable. And we’re yet to have a play with some more exotic
important to reiterate that the print continued to completion, so filaments down the road, but we will!
there weren’t hours of print wasted - making it a minor speed bump.
Of course, we need to give a major shout-out to Core Electronics
If you’re wondering what took 32 hours to print, it’s the main for their recommendation. If you’re in the market for a new
component of the marble maze that you can see in the picture. The printer, or would just like to ask questions - chat to the team at
red components were completed on the TAZ 6, while the blue body core-electronics.com.au - they know their stuff. If you’re outside
was completed on the Mini. There wasn’t any other reason for this, Australia, head to lulzbot.com. ■
other than timing - the TAZ 6 was printing the red vase when we
decided to print the maze; it’s just how it happened - they could
easily have been interchanged.
CONCLUSION
Steady
Ultra-Accurate
Voltage
Reference
GREG CHRISTENSON
Electronics Hobbyist and
Technical Director. USA.
www.barbouri.com ABOVE ▲
Mounted in a finished
case to match some of
Greg's other creations.
There are many scenarios when you
RIGHT ►
need an accurate, precise voltage Quality rotary encoder
source. This one's accurate to 0.0001V! for voltage selection.
Greg has built all sorts of amazing creations, but one that stood out That’s exceptionally precise by just about anyone’s standard! What
is an ultra-precise voltage reference. We caught up with Greg to made you embark on the task of developing your voltage reference?
understand more about his innovative creation.
I had been working on several projects that required a precise low
For someone who doesn’t quite understand what a voltage voltage sensor input, but using the actual sensor on the workbench
reference is, can you tell us what it is and what it does? was problematic. An example of this was a solar irradiance
monitoring system, which required a thermopile pyranometer and
According to Wikipedia “A voltage reference is an electronic device a precisely calibrated instrumentation amplifier. After searching
that ideally produces a fixed (constant) voltage, irrespective of for a new or used adjustable voltage standard, I realised that most
the loading on the device, power supply variations, temperature precision references were way out of my budget range. In my
changes, and the passage of time”. searching, I found a DIY programmable voltage reference, built by
C. Schnarel (uChip) on the SparkFun Electronics forum that met
The programmable voltage reference that I built has two fixed most of my requirements. I built version 1.04 of the Programmable
voltage references on the board and is designed to output a Voltage Reference based closely on uChip’s original design, but
constant fixed voltage that is programmable either from the front soon realised that I preferred an enclosed device with a panel-
panel or by a USB/serial connection. It has a DC voltage output mounted display, which along with other wants, prompted a major
of 0.001-4.095V, which can be adjusted in one millivolt (0.001V) redesign of the circuit board. ››
steps. When properly calibrated the accuracy is within +/- 100uV
(0.0001V) of the set voltage.
›› You’re using a Teensy 3.2 as the main brain. What functions does It was a little perplexing as to why it didn’t run to 5V originally, but
the Teensy perform? that makes perfect sense. What unexpected challenges did you
have along the way?
The Teensy 3.2 functions as the microprocessor and output monitor
for the board. It interfaces with the DAC using a SPI bus to set the Quite a few. The first revision 1.04 of the board only operated for
output voltage, monitors the output voltage using its internal 16-bit less than a week before the surface mount 8-bit processor failed,
ADC, sends data to the panel-mounted display using an I2C bus, and and it was extremely difficult to source the obsolete HP LED bubble
interfaces to the front panel rotary encoder and push-buttons. display used in uChip’s original board, requiring a larger display
connected external of the main board.
The Teensy 3.2 was designed and built by Paul Stoffregen of
PJRC.com, and uses a 32-bit MK20DX256VLH7 ARM Cortex-M4 I learned a lot from building the initial version and that knowledge
microcontroller manufactured by NXP Semiconductor, with a was used to improve the next revisions. Some of the changes were
maximum rated clock frequency of 72MHz. It is my favourite a socketed microcontroller board, I2C display interface that can
microcontroller board when I need more processing power and accommodate many different displays using only software changes,
memory than that provided by many of the 8-bit boards, such as output voltage monitoring, SPI interface isolation, and RGB LED
the Arduino UNO and Pro Mini boards. Teensy 3.2 is available from rotary encoder.
several distributers such as Adafruit, Little Bird Electronics, Core
Electronics, and directly from PJRC.com. The AD5060BRJZ DAC has great specifications and functionality,
but is not very DIY-friendly as it comes in an extremely tiny SOT23-8
The Teensy has been popping up in many of our features; it’s package. This makes it difficult to hand solder on the circuit board,
definitely a great board! Why did you select a ~0-4V operational and so often requires several tries to remove solder bridges.
range - was that to suit a particular application you have, or
dictated by the Teensy/supply voltage/something else? That takes a steady hand for sure! The final case is reasonably large
compared to the electronics inside. Does this serve some function,
The operational range is a compromise between my original or could you feasibly make this a “portable unit”?
preferred range of 0.001 to 5.000V, cost, and the capabilities
of the components chosen by uChip in the original design. I am The case size was partially determined by the size of some of my
finding that most of my newer projects only require a range up to other test equipment that I have built in the past. The enclosure is
3.3V anyway. I currently have two of the Programmable Voltage a Hammond model 1455N1601, and measures 6.3(L) x 4.055(W)
References, and nine other fixed voltage references to choose from. x 2.087(H) inches (160 x 103 x 53mm) and is made from extruded
aluminum. By keeping the size somewhat standardised it is easy for
The USB supply voltage was also an important factor in keeping the me to stack multiple units on top of each other.
output voltage below 5V without adding the complexity of a boost
converter and the additional filtering that would be required. It would not at all be difficult to make this a portable unit, by adding
a battery pack through a switch and connecting it to Pad1(+)
Based on the math, an output of 4,096 millivolts works out to 4,096 and Pad2(-) of the board. A trace on the Teensy microcontroller
distinct steps with 12 binary digits. With a precision onboard voltage board needs to be cut and a diode added to it, to protect its USB
reference for the DAC of 4.096V, that lets me utilise the full output connection. The extra space in the enclosure easily accommodates
range with 1 millivolt resolution per step, and have 4 bits remaining a battery pack using AA batteries.
for calibration.
ONLY ONLY
$119 $149
ONLY
BASIC KIT KJ-9340 MAKER KIT KJ-9310 ULTIMATE KIT KJ-9300
Contains a Circuit Scribe pen, six modules, battery, Take your circuit sketches to the More complex, robust circuits, which
$ 6995 workbook and accessories to get started. Explore basic
circuit concepts like conductivity and work up to creating
next level with inputs, outputs, and
signal processing in your circuits.
you can hook up to programmable
platforms like Arduino® (Arduino® not
a touch-sensitive circuit using the NPN transistor. 11pc. 17 piece. included). 32 piece.
ONLY
$ 199
THE GIZMOS & GADGETS KIT -
2ND EDITION KJ-9100
Designed for young inventors to
create and control their own app-
enabled games, pranks, and crazy
contraptions. Invent a remote-
controlled car or a caterpillar that
3995
crawls with the tap of a tablet! 16
inventions. Ages 8+. SHORT CIRCUITS BOOK - VOL.1 $
Smartphone not included. AND PROJECT KIT KJ-8502
A great way to teach kids about electronics – no soldering required!
Kit includes baseboard, springs and components to make 20+ projects,
JUST and 96-page coloured Short Circuits Vol. 1, which is complete with
$ 389 comprehensive assembly instructions and a full technical discussion
explaining exactly how the circuit works.
ALSO AVAILABLE: SHORT CIRCUITS BOOK - VOL.1 BJ-8502 $9.95
$ 6995
Battery not included.
Friendly, easy-to-use robots to learn about electronics, programming and robotics. Hours of fun and
a great way to teach "young engineers" about science, technology, engineering and mathematics
(STEM). Visit our website to see videos on how engaging these robots really are.
FROM FROM
$
12 95 3
$ 50
8
$ 95 9
$ 95
TOUCH SCREEN
TIME-LAPSE
SLIDER
shutter pins. Most cameras will also have a third focus pin. If you
applies the pulse and the gantry moves. When used for time-lapse wished to use that in your circuit it would require another opto-
photography it moves the gantry a predefined amount, fires the isolator, but it can be connected to the same plug. In this case, we
shutter, waits the required amount of time, and then moves to the will be using a 3.5mm stereo socket. Depending on your camera,
next position where it repeats the process. We have added a 0.5 you'll need a trigger cable. This could be a simple 3.5mm cable, or a
second rest period before and after the shutter fire, just to make proprietary plug, but most camera stores will sell them.
sure the platform is settled, and the motor has stopped.
The hardware of this project is the slider itself. It consists of a
If required, the camera trigger can be built as a separate unit. It V-Channel frame and a small gantry, which is driven by a long lead
requires a “high” pulse input and will close the loop on the other screw attached to a NEMA stepper motor. This motor is driven by
side. Be mindful that it does need to drive a small load, so proper a stepper motor driver; in this case, a HY-DIV268N-5A. The motor
grounding is essential. The circuit is based around the 4N25 opto- has two coils, and depending on the pulse applied to the controller
isolator. Most modern cameras have a way to trigger externally, from the RPi, the stepper motor spins forwards or backwards and
and it is as simple as creating a short-circuit across the ground and drives the gantry along the lead screw. On the gantry is two small ››
magnets that correspond to a hall effect sensor at each end. When we are using here). The calibration process will count the number
the magnet comes close to the hall effect sensor, it is activated and of steps from one end to the other, before returning itself back to
sends a signal to the RPi, indicating that it has reached the end of the “home” position. This is a practical process to complete each
its safe limits, so the motor stops turning. time, which helps to minimise any issues. This data could be stored
locally to speed up the process in future.
HOW IT WORKS
Once calibrated, you just press Home(L) or Home(R) and the unit
HALL EFFECT will traverse the entire distance of the rail. If required, you can use
the 1-4 slider to select the speed here. Within the code, you will see
The hall effect sensor consists of a small piece of metal. When it some notes relating to the delay time. Depending on the stepper
comes near a magnetic field, it begins to conduct current. This is motor chosen, you may be able to slow the unit even further. To use
amplified to become logic “high” the RPi looks for this during each the time-lapse function we need to tell the RPi two things: firstly,
loop to drive the stepper pulses. If the hall effect sensor is triggered how many shots do you want? Secondly, over what time will these
when the stepper tries to take a step, it breaks the program loop shots occur? This breaks the unit’s steps down to the number
and stops. required for the length/number of shots required.
OPTO-ISOLATORS / CAMERA TRIGGER Next, we tell it the total time of the time-lapse in seconds 100/
(60*60). This will give us the delay after each shot (note: there is a
Most modern mid to pro level cameras will include a port to enable built-in pause of 0.5 seconds before and after each camera pulse, to
triggering of the camera without touching it. The primary function ensure the gantry is stable, since the stepper motor can introduce
of this is to avoid camera shake from your finger leaving the shutter vibration).
button (which occurs even when the camera is on a tripod), during
long exposures. We have built a circuit around triggering this remote Here is a basic flow chart of the system logic:
option directly from the RPi (it could be easily used with an Arduino
or 5V signal source). The camera input requires a simple short
circuit (i.e. a switch). However, this is not so straight forward when
using it with a micro controller, as sending a pin high is not the POWER
same thing. We need to trigger the flow of energy from one part of UP
the camera to another. This could be achieved with a relay, but they
require bulk and power to run. We do not need anything more than
a few mA, so the simplest solution is an opto-isolator. The opto-
isolator works by applying a voltage to one side of the unit, which is MOVE TO COUNT STEPS
CALIBRATE
connected internally to an LED. On the other side is a receiver, which HOME TO END
switches on a transistor when the load is detected. This allows
current to flow on the other two output pins, without contact to the
original input signal. This will not work as a switch, and requires
there to be some load (which is provided by the camera). However,
the major benefit is that it protects the camera from any stray READY RETURN HOME
voltages that may be present. This is an important consideration
when using stepper motors, as a stepper (just like a standard
motor) can act as a generator and create serious power if you move
it by hand.
GO!
The RPi has several functions, but primarily it drives the stepper via
the control module. Two key variables drive the number of steps,
YES
and the speed in which the steps are taken. We achieve this by
creating a loop that drives the output high, pauses briefly before MOVE PAUSE/
taking it low, and then repeats the process. The RPi also selects the END REACHED
LENGTH/STEPS TRIGGER
direction of the motors, and pulls the pin high or low to control it.
NO
The code and GUI are used to control key elements of the project. On
boot, the system will “home” itself, and return to the right (stepper)
side of the unit. Since all units will vary, the next step is to calibrate
the unit (this gives you the option to extend the length beyond what
THE BUILD For our build we simply purchased a gantry kit from:
www.makerstore.com.au/product/c-beam-1000-actuator-kit/ - it
This system will use just about any gantry style setup you like, so comes with everything to make a strong gantry including stepper
long as it uses a four-wire stepper motor, and you can attach hall motor, in barely a coffee break.
effect switches to each end. It doesn't particularly matter if it's
belt-drven, leadscrew-driven, has four wheels or slide-bearings. It We did recycle our stepper motor controller however. Ours was left
can be brand new, or recycled from another project - it really doesn't over from another CNC project. Realistically however, any 4-wire
matter. stepper controller with this sort of configuration will work as long as
the drive voltage is compatible with your stepper motor.
Perhaps one of the most awesome aspects of this project is that our
code is designed to auto-detect the travel of your gantry. It counts
and moves in steps, not actual measurements, so it can feasibly
work with any hardware configuration, from 30cm to 3m (and
beyond!). For this reason, we won’t be describing the gantry build
itself in any great detail, as it’s very feasible you’ll be using different
hardware, simple follow the instructions that come with your kit. ››
SDA 5V
SCL GND
#4 TXD
SW1
GND RXD
SW2
#17 #18 SW4
HY - DIV 268N - 5A
#27 GND SW5
SW6
#22 #23
3.3V #24
DC-
SCLK CEO
GND CE1
B-
EED EEC
#5 GND B+
#6 #12
A-
#13 GND
#19 #16 A+
#26 #20
EN+
GND #21
EN-
PUL+
PUL-
DIR+
4N25
521Q
DUR-
BUILDING THE CIRCUIT we need to trigger the camera using a simple switch. The original
solution was a relay, but they are big, bulky and can often draw
The build is divided into three parts: the first circuit is used to drive relatively large amounts of power. The solution is an opto-isolator.
the stepper motor, its controller and the hall effects. The second is For this project, we will be using the low-cost 4N25. It is a six-pin
the camera trigger; and finally the rail and gantry. package, but we will be using just four pins. The INT side connects
to the RPi, and has an LED to indicate that the signal has been
The first part of the circuit connects to the HY-DIV268N-5A. This is received. It also has a 390ohm resistor, which drives the LED we are
a 5A four-wire stepper motor controller. As previously noted, you using, as well as the LED inside the opto-isolator. We then connect
don’t need to use this particular stepper driver. The stepper driver our output to pins 4 and 5 of the opto-isolator .
simply allows you to control the heavy power required to action
the signals being sent from the RPi. We need to connect pin 16 to For the camera in use, we have used a 3.5mm stereo socket. This
the enable pin, 18 to the direction pin, 23 to the pulse pin, and the allows you to use a simple 3.5mm cable if your camera supports
remaining to ground. In this case, we have used a 6-pin header to one, or a 3.5mm adaptor to whatever proprietary plug your camera
make connecting the driving elements. Next, we have added two requires. We recommend researching what is required for your
3-pin headers; one for each hall effect sensor. These then connect particular camera. An adaptor cable should be readily available
to the sensor located on each end of the rail. We have laid them out from most camera stores to suit your camera. Be mindful that
to replicate the pin configuration of the hall effect modules. polarity matters here, and you need to make sure that the ground is
connected correctly. Reverse the connection if need be.
CAMERA TRIGGER
Regardless of precisely how your gantry works, at each end of the
Most modern cameras with an electronic trigger simply require rail needs to be a hall effect sensor. We have used the prebuilt
a switch or a dead short across the points, to trigger the shutter. 3-pin 5V modules to make connections easier, but you can use
However, when we connect this to the micro controller we cannot the straight TO-220 packaged version without PCB too. The major
simply run a “high” 5V signal into this, as it will not work and you benefit of Hall Effect sensors over tactile switches is they're non-
risk damaging your (sometimes expensive) equipment. Instead, contact (so they'll never wear out), and they don't require such
precision alignment. We simply mounted ours using a cable tie and
5V
OPTO
24
2 4N25 5
RASPBERRY PI
25
3 (NC) 4
18
23
16
OUT OUT SLEEVE
DIR-
DIR+
PV-
PV+
EN-
EN+
5V 5V
STEPPER
a spare bracket. Gaffa tape or just about anything else will work.
Just note that the little red LEDs will give you indication of power
and activation of the sensor itself - very useful for debugging.
Next, you need to connect the stepper motor coils to your stepper
motor driver. A+/A-, B+/B-. Please consult your stepper motor’s
documentation. We found that even though we were using a to be interrupted, so an on-screen STOP button won't work with
common stepper, the coil wire colours were often different. the current system configuration. For this reason, a hardware
emergency stop button is a good idea. It interrupts the ENABLE pin
Finally, connect the stepper motor to power. Your system should on the stepper motor controller, shutting off the stepper motor as
now be ready to use! soon as it's pressed - regardless of what the Raspberry Pi is trying
to do.
SAFETY CONSIDERATIONS
Using this method provides a safe method in case of any undesired
While it's not absolutely imperative to operation, we thought it operation. It could be that a wire came loose and your stepper
would be useful to note . As mentioned before Tkinter doesn't like travels the wrong way, a hall effect sensor doesn't work, or worse ››
someone gets a finger caught in a pinch point. While the stepper than this (really only a consideration for astrophotography or
motor being used is relatively low torque, if could still do some night landscapes). Once you have your calculations set and your
damage. At the very least, it could damage the slider hardware. calibration complete, connect your camera and press GO!
Once you have the hardware connected, please open the DIYODE_ Once you have captured everything you want, you’ll need to use your
time_lapse_slider.py file and run. You will be greeted by several video editing software to compile the time-lapse photo sequence
buttons on a GUI, optimised for the Raspberry Pi 7” Touchscreen. into a video. When you create your images, you’ll end up with quite
large files - well beyond 1080p, so you can easily create ultra-high
Before any operation occurs, the system must calibrate itself by definition video from it. We have created some 4K video time-lapses,
travelling the gantry and back. However, if it does not or you do not which demonstrate this capability.
have the unit powered up, just press the calibrate button.
Creating a time-lapse movie is dependent on the software you use,
The GO button will not work until it is calibrated. In order to set and as such we have not included it in this article. However, we would
the system to run through operation, simply specify the number recommend Final Cut Pro or iMovie on a Mac, and Adobe Premiere or
of frames you require and the total time duration you'll leave the Windows Movie Maker on Windows machines. It is beyond the scope
system running for (eg, 10 frames, over 10 minutes). If you are of this article to provide a detailed guide on each one. Once you have
using video and don't require camera triggering, just select the all of your images, you will need to import them all into your software
time and set the frames to 1 or 0. You can feasibly also omit any of choice and commence creating your time-lapse.
electrical connection between your camera and the slider, simply
remember to start and stop recording before and after the slider WHERE TO FROM HERE?
motion.
BELT DRIVE: For this project we used a lead screw, which offers low
CAMERA SETTINGS maintenance and bulletproof consistency; however, we did notice
vibrations were occasionally produced which caused our motion
The logic here assumes a few things. Firstly, all the circuit does is video to be shaky at times. Using a belt drive would eliminate this
trigger your camera. The code could easily be modified to control and make rating more smooth. However, it does come with an
the exposure, but we would question its accuracy at anything under increase in maintenance costs.
five seconds. It is designed for the exposure to be set on the camera
itself, and so simply replicates the triggering the shutter. Be mindful Y OR Z AXIS: Why not add in a second or third stepper or servo,
that you need to have the duration of the shutter set to be less than or create even more dynamic movement with pan and tilt of the
the delay of the slider, otherwise you will end up with significant camera on the gantry?
blurring of your image. More steps or shots does not equal more
delay; more delay comes through the total time (delay time). We RAMP UP / DOWN: One thing that will make your videos look even
have given the frame output time in the GUI in seconds. You also more professional is to ramp the movement in and out. This is
need to remember that there is a 0.5-second delay each side of that easily done in the software; however, it does become more complex
delay. in the GUI. It is as simple as a start speed and end speed, and
incrementing or decrementing the variables as required.
Seconds per frame will come up when you are calculating your
time-lapse. Please ensure that your calculated exposure is shorter MULTI-THREADING: The GUI has one major limitation. Once the
operation has started, you are unable to stop operation due to the
way Python and Tkinter handles its events. The alternative would
be to start the movement functions as a separate thread to the GUI
main loop. This method could result in increased functional control
and enable an on screen emergency stop. However, virtually all
stepper motors have an “enable” pin, including our test circuit. A
hardware method to disrupt the enable pin means everything stops
if you hit that emergency button. The software may continue to run,
but if provides you with an emergency stop if your hardware is about
to do something you don’t want. ■
WANT MORE?
To download the code and watch videos, visit:
https://diyode.io/003wknf
Low Voltage
Mains
Should it be the
New Standard?
In the age of logic-level electronics, USB-
powered everything, does it still make
sense for high voltage mains power to be
the standard in buildings? - by Rob Bell
It’s been well over 100 years since electricity was first introduced This trend is increasingly acknowledged with the availability of
to buildings, and high voltage AC distribution rapidly became the adapters and mains wall plates that provide mains power, as well as
global standard (rightly so). However when this occurred, electricity USB power in a standard fitting. The mains USB caters for the fact
usage was really focused on lighting, to replace oil lamps and such. that in many households there’s a battle, but it’s not over the mains
Of course, it gradually moved to appliances too. Regardless of the outlet so much, it’s now over an available USB outlet!
original intention, there could never have been a prediction that low
voltage appliances would become so common within a household. LIGHTING VERSUS POWER CIRCUITS
Even in the 1980s, computers were large and expensive, with the
VCR often the most complicated piece of technology in the house. There are different considerations required for the lighting circuit in
a building when compared to the power circuits. Lighting, even in
High voltage mains wiring makes sense for power-hungry an old-school incandescent scenario, typically draws far less power,
connections such as a refrigerator, air conditioner, kitchen and and doesn’t have the drastic changes in load like a mains circuit has
laundry appliances, and a few other things. But for the majority of with large motors, heating elements, and other high-load systems.
appliances now found in a household, would low voltage wiring In a modern world of LED lighting however, the power consumption
make more sense? for lighting continues to fall, with the power of a conventional
lightbulb now capable of illuminating every room an entire house!
Consider how many appliances in your house are truly mains-
powered: the WiFi router, the bedside lamp, the phone charger? All The demands on the lighting installation also remain flexible, and
of these things are independently reducing mains voltage to 5-12V are far less than for mains outlets. While the layout of a lounge room
(usually) with their own plugpack transformers. may change as furniture and fixtures are updated, the same is rarely
28 Issue 003 September 2017 diyodemag.com
MOONSHOTS
true for lighting. For rental properties and home owners alike, the LOW HANGING FRUIT
lighting fixtures are accepted as a permanent installation that are
often only changed out of necessity or during renovations. There’s a huge additional benefit of a 12V dominant system:
renewables. As we push further to renewable energy, it’s
Consider for a moment, if your house lighting was wired with 12VDC increasingly common to generate or store wind or solar energy
from the meter box. You would have a safe, low voltage, accessible locally in batteries at 12VDC. By removing the need to invert this
power source that you couldn’t really get into trouble with. You could power from 12V back up to mains voltages, (which are often
wire in new lights yourself without requiring an electrician, and then converted back down again to actually power something),
even for electricians doing the job, there is a marked improvement substantial efficiency can be gained which would otherwise be lost
in workplace health and safety. You would have less EMF and heat with the complicated electronics required to do so (especially when
generation in the roof cavity from all those lighting transformers, there’s no other benefit from the conversion).
which are most likely already there, and plug-in LED globes would
be cheaper (since a 12V driver is simpler and cheaper to produce Indeed, whenever possible many off-grid installations do away with
than a mains driver). mains power and focus on low voltage lighting and appliances. It’s
safer, more energy efficient, and just makes sense.
Indeed for many devices around the house, you could use a similar
12V circuit to provide low voltage outlets. Plugpacks could be
replaced with simple (or simpler) cables. You can have one highly
efficient mains to 12V (or 5V, or both) converter in your mains box,
which is distributed around the house (with its own 12V circuit
breakers, of course). Even a standard computer converts the mains
power to 12V and 5V rails; this would further be simplified if 12V
power was readily available.
CHALLENGES
There is little doubt that high voltage mains are the best option Will we see a new connection standard to support all low voltage
for refrigeration, electronic heating, pool pumps, and other devices? Arguably USB Type-C is attempting to be that standard
devices with high power requirements. But outside of long with its ability to throughput much greater power than previous
range distribution and high consumption devices, a 12V system USB iterations; but there are very real limits to its capabilities
provides some huge benefits. for power. This is largely due to its design, primarily as a data
connector and not as a power connector. In my own personal
In reality, there is little stopping someone from doing this experience I’ve also struggled with some connectivity issues as
themselves, especially for low voltage lighting. Perhaps the the connector wears.
biggest challenge is the lack of a DC connectivity standard.
Even among common DC connectors you have 2.1mm, 2.5mm, Are we simply destined for a world of endless adapters,
and just about every other size between 1.0 and 5mm. Even converters and mismatched frustrations? Or will we see a new,
with the dominant standard of a cigarette lighter/vehicle- low voltage standard reign supreme, ushering in new standards
powered 12V sockets, there are also Merit connectors, and the for efficiency and safety through buildings around the world?
increasing popularity of Anderson connectors for their reliability Only time will tell. ■
and support of high current. Of course, there are many others,
including PV connectors common in solar installations too. GOT SOMETHING TO SAY?
To discuss this edition of Moonshots, visit::
One major benefit GPO mains connections have going for them https://diyode.io/003fdwx
is, they are relatively standard. Within most countries, fairly
consistent standards exist. Sure, there are some worldwide
variances, but at least that’s limited to about three types.
diyodemag.com Issue 003 September 2017 29
FEATURE
ELECTRONIC
HOMEBREW
Building Your
If building your own computer is a rite of passage, then Matt is well
on his way. His Homebrew 68K computer is still in progress, but it’s
a journey of exploration through the hardware that surrounds us. We
Own Computer
had a chat to Matt about this fascinating process.
It’s an interesting world, and can make you a better coder! How did
you get started?
The first thing I did was buy a couple of MC68000P12 chips from
Now's not the time to discover you
eBay, and then didn’t do anything else for a month or two while
missed a critical wire.
I worked out where to start. I read about other 68k RetroBrew
projects and discovered that the book “68000 Microcomputer
Systems: Designing and Troubleshooting” by Alan D. Wilcox is held
in high regard, and managed to grab a copy through Amazon. I
picked up a copy for around 40USD (although at the time of writing
this, the cheapest copy is listed at 146USD). I read the first half
of that book a couple of times, and then set about buying more
hardware, namely some 7400 series chips, as well some EEPROM
and SRAM chips.
That’s a great find. What will be the critical success point for this
project?
Awesome - RAM is a critical stage to get working! What knowledge It’s an Arduino UNO that I got in a starter kit some years back. I’d
do you now have that would make it easier to approach this project done a few experiments with it but then never really found a real
a second time around? project. Programming the EEPROM chips seemed like a reasonably
simple process judging by the data sheet, and I’d seen others do
I’m not sure there’s one key piece of knowledge I’ve gained; it’s similar things online so I figured I’d just get stuck in and see if I
more an understanding of how a whole (or as whole as it is right could create a shield to do the job for me. It started life as a single
now) system fits together. I’ve been tackling a small piece at a time, EEPROM chip on a breadboard with a few wires to the Arduino and
but that’s meant it’s been more organic than by design for the most then rapidly took on a life of it’s own.
part. Perhaps doing a simpler project first, with an 8-bit processor
and smaller busses would have prepared me a little more. One trap It’s fairly easy to find an EEPROM programmer. Was your approach
I definitely fell into was thinking that breadboards make things cost-driven, or a quest for knowledge like the 68k?
easy to change - sure, nothing’s soldered or held in place by a wire
wrap nest, but when you’ve got so many wired on a board, some A little of both. The programmers I could find that were compatible
get buried, and then if you decide you’d have been better off with a with the chips I bought (Atmel 32KB chips - AT28C256) were
core IC (such as a 64-pin DIP 68k CPU for instance) elsewhere, then surprisingly expensive, compared to the one I’d already purchased.
you’re probably out of luck. We’re only talking around 60AUD or so, but it seemed like overkill if
I could learn something instead, and it seemed like a good excuse
Are you still primarily focused on the 68k, or have you put it on hold, to do something that seemed “easy” in comparison to the more
for something else? If so - give us all the details! daunting 68k project.
I’m pretty sure I could comfortably fill a 40+ hour week with my What knowledge have you gained that will help you bring EEPROM
hobby projects, but right now this is my focus. Breadboard solutions to your 68k?
are ephemeral by their nature so I don’t want to drop this until it’s
working on a PCB. If I fail to do that, I just know I’ll have a very hard A surprisingly large amount. The first issue I hit was not having
time picking it up again later down the line. Any software developer enough IO pins on the Arduino to be able to use much of the
will be able to tell you that a five-minute distraction is more like a memory on the EEPROM chips. With a few control lines and the 8
two-hour distraction: task switching is expensive when it causes you IO pins taken care of I wasn’t close to having 15 free pins for the
to lose track of your state of mind. This project is similar, just with address lines. When you’re dealing with powers of two any missing
longer time frames. My other “current” project is one that I’d put pins on the top end (high address lines) are going to really hurt.
on hold for this. It’s a platformer game for the Atari STE, tentatively From investigating what others had done (Quinn Dunki was a very
called “Dave the Dragon”. valuable source of information), I discovered shift registers and got
to know them, which has been handy because I use one of the same
Absolutely - i think we've all been guilty of having too many projects registers in the DTACK circuit for the 68k.
going at once, it's an industry hazard! But occasionally you get
to circle back to an old project, and you have magically found the Bypass capacitors were also new to me. For those who don’t know,
problem that caused you to put it on hold anyway! they’re capacitors you put across power pins on an IC to help soak
up any voltage fluctuations caused by other ICs that are busy doing
their thing. It turns out posting PCB designs online is a great way to
get plenty of people pointing such omissions out to you!
That leads me onto the major part of the learning exercise: about) and waited. I received an email a day later to say I hadn’t
designing a PCB. I’d never really drawn up anything but simple included a drill file, which is basically a map of all the holes that
schematics in my life (and then on paper), so I spent most evenings need to be drilled into a PCB so that you can mount components.
in a two-week period experimenting with different schematics After sending that off I eagerly watched the manufacturing progress
and PCB design software packages. It seems everyone has their updates and after around two weeks a package arrived with my
favourite software, and every piece of software has it’s own quirks. boards. I soldered one up that evening, which was another first,
Some of the UI decisions completely baffled me, for instance, when and discovered that roughly eye-balling the space required for a ZIF
looking at KiCad. EAGLE was something else I played with, but socket on the PCB layout wasn’t the smartest decision; everything fit
the first thing I used which I felt naturally comfortable with was but to say it’s cosy would be an understatement!
DipTrace. It’s commercial software but with a free offering, subject
to some limitations that I was never going to need (“All features and If that’s the worst hiccup then we’d still call it a success! If you
libraries, 300 pins and 2 signal layers, non-profit use only”). This started it from scratch, would you still approach it the same way?
could well become an issue with the larger 68k project, but I’ll deal
with that when I get to it. That’s hard to say. If I did need another programmer I may just
buy one as the overall programming process would be smoother -
DipTrace not only seemed to have the smartest wiring tools in the simply providing a binary file to a prebuilt piece of software is a bit
schematic, but it also made it very easy to create a PCB layout more pleasant than my solution. Right now the binary for the ROM
from a schematic, as well as update that layout as the schematic gets built into the Arduino code, and then the “interface” consists
changes. It’s got an autorouter but routing was something that had of a serial IO based menu, so that you can send commands to the
always fascinated me, so after five or six attempts I finally routed Arduino from a PC. All that aside, if I knew I’d learn as much as I did
everything, and had something to show to the world for feedback. this time around, then I wouldn’t hesitate to get stuck in. Rabbit
After a few tweaks (bypass capacitors *cough*) I decided it was holes can be pretty valuable sometimes.
ready. I should definitely have done more double checking, but I was
getting a bit excited and wanted the boards made. DIY solutions That’s awesome. We wish success as you finish off your project! ■
seemed a bit messy and fussy, and I found I could get 10 boards
created and delivered by PCBWay for 16USD, which seemed too WANT MORE?
good to be true. I uploaded my Gerber files (something else I learned For more images, or to discuss this feature, visit:
https://diyode.io/003yzqg
A five-minute
distraction is
more like a two-
hour distraction:
task switching
is expensive .
NEW!
$ 29 .95
NEW!
K 9640
30
$
The MegaBox allows an Arduino UNO or Mega to be plugged into $ and easy to use for students in coding class rooms. It
even connects to Arduino and Raspberry Pi! Includes
it, along with a shield allowing you to build a design into a finished USB lead and battery pack.
case. Plus it also features a 16x2 LCD, four buttons, rotary encoder, dual 2A 5V
relay outs. All pins broken out to headers for connection to breakouts. Z 6308
NEW! $ 49.95
69 .95 NEW!
$
Z 6303
3D Gesture Control For Raspberry Pi®
NEW!
$ 24 .85
H 8950
FlickHAT is a 3D tracking and gesture HAT that lets you control
the Raspberry Pi with a swipe, tap or flick your wrist. Detects your
gestures up to 15cm away in 3D space. Also works as a tap/touch
Quattro Raspberry Pi Case sensor pad.
Stylish VESA mountable square design with 2.5” HDD
bay underneath. Ideal Raspberry Pi media centre case. $59.95
SAVE 24%
$ 45
Raspberry Pi® Zero W Kit NEW!
$37.95
The Pi Zero W offers amazing power and features from a compact board including
Bluetooth and 802.11b/g /n wi-fi. 1GHz CPU with 512MB of RAM. Mini HDMI &
USB OTG on board. Kit includes Zero W board, header pins (unsoldered), case, 16GB
D 0507
D 0505
$ 29
SD card (with NOOBs), mini HDMI adaptor and USB adapter. $72 Z 6420
Super Slim Battery Banks
Instant recharge for your phone. Slimline design, fits easily in your
pocket. D 0507: Dual USB 1A and 2A outputs, 5600mAH.
Raspberry Pi Desktop PC Case
NEW! Turn the Raspberry Pi into a desktop computer with this
D 0505: Single USB 1A output, 3500mAH.
case & expansion board. Provides an intelligent power
controller, an RTC & a mSATA SSD hard drive interface.
$115
NEW! $ 65
Z 6313
Raspberry Pi®
$ 11ea SAVE $50
Z 6412 Standard, Z 6413 SOIC28 Type
Starter Platform Kit Prototyping CaseHAT
A handy starter kit for educators or Pi newbies. We made a few improvements to our ProtoHAT and
Includes a Raspberry Pi board, red acrylic Arduino Display & Sensor DIY Kit
125
came up with a version that fits inside an official
base, 5V 3A power supply, GPIO breakout &
breadboard. K 9620 $ Raspberry Pi case with the lid on (shown here without
the lid). SOIC28 type has small area for an SMD chip.
Includes a UNO compatible dev board, 16x2 LCD module,
breadboard & an array of sensors for experimenting!
$ 209 $245
M 8200A 0-30V 3A M 8205 0-30V 5A
uring internal, external
and depth dimensions.
0.01mm, 0.0005” and
1/128th” display.
speed between 8000 and 33000
RPM. Included is a massive accessory
kit of grinding wheels, drills, cutters,
sanding discs, polishing pads and
Linear Lab Power Supplies more! And it all stows safely away in
40
T 2247A a hard plastic carry case.
Our most popular models! Fully adjustable with LCD meters for $
precision adjustments. Great for R&D and workshops. • Linear
toroidal design • Voltage & current knobs • Fixed 12V & 5V out-
put rails • Fully regulated • Short circuit & overload protection. SAVE 27%
$ 74.95 T 2120
SAVE $50!
$549 Q 1283 Q 1130A
NEW!
T 1480
$16.50
$ 39.95
X 0435
T 2356
19.95
$ $ 14
$13.50 $17.95 $69.95 $24.95 Shift dust instantly!
Rotating PCB Holder
$ 11 $13 $ 55 $19 A must have for the soldering enthusiast!
Work on boards up to 200 x 140mm. Heavy
This air blower bulb quickly removes dust
and debris from boards. Includes fine nozzle
T 2401 25W T 2405 40W T 2487 50W T 2483 80W springloaded base with rubber feet. and brush attachments.
ExtraDrive
Pedal Kit Races $19.95 $16.95
$16.50 toward a
Build your own
analog effects pedal $ 13 K 8112
light source K 8134 $ 16 $ 13
and tweak it you suit
your needs! Controls Shaking Dice Kit Robo-Voice Changer Kit
$110 level, tone, symettric/ Running Micro Bug Kit No push button required, just give Make your voice sound like a robot
asymettric, distortion Features two open chassis sub-miniature motors with it a shake! Slowly rolls to a stop with this tiny module. Adjustable
$95 K 8124
& true bypass. Tough
diecast case.
adjustable light sensitivity. Includes LED eyes. Requires
2xAAA batteries (S 4904 lithium $4.95 2pk). 100x60mm.
to show the final value. Requires
CR2032 battery (S4999B $2.95)
pitch and vibrato effect. Requires 9V
battery (S 4970B $3.95).
Builder Bitz.
$14.95
$48 $11.95
$ 11 9
40 $
Z 6345 Z 6262
$ Z 6550
Screen & Keypad Shield
Arduino Expansion Shield for R-Pi A 16x2 black character screen with green Sensor Connection Shield $34.50
backlight. Push buttons are provided for up, A stackable sensor connection board for
Mash the two worlds of Arduino and Raspberry Pi
together using this handy expansion shield with on- down, left, right and select. Ideal for scrolling
and selecting menu options.
Arduino. Features quick header connec-
tions for digital I/O pins and analog inputs.
$ 24
board atmega32u4 and X-bee slot. K 1090 2WD
Vehicle Base Builder Kits
With individual motors for each wheel with $44.50
acrylic base for mounting control and sensor
40 Way Pin
boards. Ideal base for your own Arduino
robo-car design. Includes battery holder.
$ 30
$14 K 1092 4WD
Headers
Cut to any length. 20 for
$19.95
2.54mm pitch. P 5430 $ 10 $ 15 Great for auto wiring
K 1102
$ 27.50
connection every time. 17.5A rated @ 450V.
$ 25
W 0888
NEW!
J 0902
Standard P 8225 5
$ .95 P 1030
NEW! $7.50
$ 13.75 $ 6 Glue Backed
Heatshrink Pack
Pull Type Solenoids
J 0900 Ultra mini
In-line DC Power Switch 7 Pk of Mini Breadboards Great for sealing out dust and moisture. 106pcs of 45 &
Ideal for any project requiring a pulling actuator. Fitted with 2.1mm plug and socket. Quick and 55 hole bradboards for instant solderless 75mm lengths of red & black. 3.2 to 12.7mm sizes. 3:1
12V DC operating voltage. Full specs on website. easy way to turn devices on and off. component connection. shrink ratio.
Prices valid until September 30th 2017 | 1300 797 007 | www.altronics.com.au
Find your nearest reseller at: www.altronics.com.au/resellers
© Altronics 2017. E&OE. Prices stated herein are only valid until date shown or until stocks run out. Prices include GST and exclude freight and insurance. See latest catalogue for freight rates. Please Note: Resellers have to pay the cost
of freight and insurance and therefore the range of stocked products & prices charged by individual resellers may vary from our catalogue. B 0088
FUNDAMENTALS
KEEPING IT
REGULAR
Not all power supplies are stable, or
provide the right voltage. But there’s an
easy way to solve this. - by Daniel Koch
For many makers, getting the right voltage and an output. Power goes in at one voltage
for their projects is one of the biggest and comes out at a regulated lower voltage.
challenges. While many programmable In practice, there are some components
boards like Arduino or Raspberry Pi run on required around this but the basic principle
either 3.3V or 5V, many higher-powered is very simple. There are some terms and
output devices such as motors, relays or conditions, so it isn’t all smooth sailing, but
LED light arrays need 12V. In many other first, let’s look at the devices themselves.
cases, you may wish to be running a board
from a battery source, the voltage of which The most common series of regulators
may not match your requirements. available on the Australian market is the
LM78XX series. These are three-pin positive
However, there are solutions to this voltage regulators, and are available in a
challenge. The first of which is a classic range of fixed voltages indicated by the last
component known to electronics engineers two digits of the part number; that is, where
and hobbyists alike, called the voltage the XX appears above. They have a standard
regulator. One type of voltage regulator is current limit of 1A.
a three-pin device with an input, a ground, INPUT GND OUTPUT
1 3
Input at least OUTPUT
+14.5V +12V
7812
0V
Once you have established which pin is the INPUT, which is the
GROUND, and which is the OUTPUT, you simply connect them
to where they need to go, then add a couple of capacitors, as
suggested in the data sheet. What you add here varies with
application. On the input, an electrolytic capacitor of around 100uF
is ideal, followed by a 10µF and 100nF pair across the output. This
is a worst-case scenario, and the capacitors help to cope with
sudden fluctuations and transients in the supply. ››
›› If the supply falls below the threshold of 2.5V above the output,
6 Vin IN OUT +5V
regulation is lost; so these capacitors stabilise the supply to ensure
LM317
that this does not happen. If your application is unlikely to feature
any such transients, then run with 10µF [4] on the input, and 100nF R1
on the output. National Semiconductor, in fact, claim their products 240R
can be run without any capacitors. Of course, all the information in C1 C2 +
this paragraph can vary, so check the data sheet, preferably from 0.1µF 1µF
the correct manufacturer, for the device you have.
R2
BELOW ▼
ESP8266 WiFi shield
provides connectivity.
MQTT
Light
Switch
Everything has an app to control it these days, but
wiring in electrical hardware to control a mains light
switch is still beyond the reach of most people who
aren’t actually qualified electricians. Here we put
together some hardware and software, which makes
controlling light switches (and other devices) a less
shocking option. - by Tim Blythman
OVERVIEW
For mains devices that run from a power point, it’s not quite as There are three separate parts to this project, which correspond to
difficult to add some sort of remote controlled power point without the three different roles that can exist in a system that operates on
worrying about messing with risky wiring, because the options are, the MQTT protocol. A topic and message are published to a broker,
literally, plug and play. If you want to interface into a light switch which then forwards that message on to a subscriber (provided
it usually means directly connecting to the wiring, with a relay the subscriber has subscribed to that topic). In this case, I use an
to switch the power. Adding some extra hardware usually makes Android app to publish the custom data by sending a message to a
manual control more difficult as well. topic, which is received by a single board computer running a broker
program. An Arduino connected to a WiFi shield subscribes to the
This project creates a workaround, avoiding these two problems. topic on the broker, and if it receives a message that corresponds
The interface to the light switch does not require any mains wiring, to a command, it moves a servo motor to briefly operate a switch. It
and still allows manual control of the switch. This project uses then moves the servo arm out of the way so that the switch can be
the MQTT protocol because there are apps available that can be manually operated. The way that MQTT can transmit different topics
customised to do what we need, and it’s also a very simple protocol means that different devices can be configured to control or be
that an Arduino board can handle. controlled, while all passing through the same broker. This system
lends itself to many small, simple devices like an Arduino attaching
themselves to a single more sophisticated broker, which can do all
the hard work of managing the messages.
HOW IT WORKS implementation from scratch. See the "What the Tech" article for a
detailed discussion about the MQTT protocol and how it works.
The heart of any system using MQTT is a broker which mediates
all communication. In this project, it is nothing more than a The general sequence of events is that the Arduino connects to the
program running on a device on the network. For the sake of WiFi network, then connects to the broker and sends it a connect
security, it is best that the broker is kept to being accessible message. When the broker sends the “connack” message, the
only from inside the network. For testing purposes there are also Arduino sends a subscribe request, to which the broker replies
MQTT brokers on the internet which can be used, such as test. with a “suback” message. The Arduino is now waiting for incoming
mosquitto.org. If you don’t have your own broker set up, you can messages, and when it receives a notification that matches one
use this broker [1]. that it’s looking for, it activates one of the servo motors to operate
the switch. The Arduino also occasionally sends a ping request to
keep the connection alive. If the connection is broken, the Arduino
1
attempts to reconnect.
The electronics are easy to build - the WiFi shield simply stacks on
top of the Leonardo, and the servos can be plugged straight into the
digital pin header breakouts, as they have the same pinout as the
servo motors I’m using. I needed to extend the servo wires a short
To control this project, we need something that can publish distance, so I used plug-socket jumper wires to do this.
messages to the broker. I found an Android app called MQTT
Dashboard [2], which was easy to configure and operate, and The mechanical side of hardware is made of two 9G servo motors,
lets me operate the switches from a mobile device. After setting which operate to actuate opposite sides of the switch. I had initially
the address of the broker, a number of buttons (or sliders and thought it might work with just one servo, but these have a throw
other controls) can be configured to publish custom messages of barely 180°, which isn’t enough to swing all the way around and
to any topic. The app can also be configured to subscribe to operate both sides of the switch toggle.
topics as well; for example, it could be set up to monitor a
sensor variable such as temperature. If you don’t have this app Each of the servos is only activated for a second, while it moves
or another one, there are also command line alternatives, which the switch and then gets returned out of the way and into an idle
could be activated from a shortcut on a computer, and are also position, which saves on power and also means that the servo horns
handy for testing. are free to move if they get in the way.
Probably the most involved part of the build is the Arduino-based THE BUILD
subscriber, which responds to messages from the broker. To
help understand the MQTT protocol better, I worked to build the PARTS REQUIRED: JAYCAR ALTRONICS
1 x Arduino UNO XC4410 Z6280
1 x ESP8266 Based WiFi Shield XC4614 -
2
2 x 9G Servo Motor YM2758 Z6392
Double Sided Tape NM2823 T2985
MQTT BROKER
With the core of any MQTT system being the broker, it is a good idea
to set this up first, as you’ll need the address of the broker, at least,
to set up the app and Arduino. As noted above, all that’s necessary
is to install the “mosquitto” package of the broker and clients for
a device on the network, and make sure it is running as a service
that will be activated when that device boots. The address you will
need to use for the rest of the setup is simply the IP address of this
device. To test the broker, you can manually run commands. These
same commands can also be used to test the Arduino later if you
can’t get the app working. I’ve used these on the Yun shield, but
they might be slightly different on other versions of the mosquitto
software.
Open one console and run the following, replacing the IP address
with your broker’s IP address (or domain name if using a public
service): ››
PROJECT
These have the effect of publishing the messages “off” and “on” to delay(2000);
the “lightswitch” topic. You should see “on” and “off” appear in the s.write(180);
other console window. If you are getting this, then your broker is delay(2000);
THE CONTROLLER
The servo motors have a serrated shaft, so it was fairly easy to set
the servo motor to the “actuate” position, then reposition the arm to
a suitable location.
Mini Servo
Once the correct position is found, the arms can be fixed in place
with a screw that’s included in the pack.
The next step is to attach the servos to the WiFi Shield, then plug the
WiFi Shield into the Leonardo. Check the polarity of the servos: the
brown wire goes into the “G” row, red into the “5V” row and signal
wire into the “D” row. I’ve used D2 and D3 but these can be changed
Mini Servo
in the code. The other changes you will probably need to make to
the code will be the name and password of your WiFi network, and
the IP address of your broker.
ON
//spec WIFI network and MQTT server
ON
13 12 11 10 9 8 7 6 5 4 3 2
D
ESP13 Shield
5V
G
SW1 #define SSIDNAME “SSID”
#define SSIDPWD “PASSWORD”
TX RX G 5V
G
5V
RST
The MQTT port of 1883 should be the default, but can be changed if
The Arduino hardware is next. Most of the assembly is quite necessary. Upload the sketch to the Leonardo and monitor the serial
straightforward. The first tricky part I found was positioning the port for debugging messages [3]. If the subscribe part completes
servo motors to consistently actuate the switch. In my home I have successfully, try the publish commands on the console from earlier.
the older style light switches, which have a smaller toggle than These should be detected by the Arduino and displayed in the serial
some of the newer switches, so you may find this is easier if your port. If you have the servo motors attached, they should try to move.
house is newer. If you have one of the newer “Clipsal” removable
type plates, it might be feasible to glue the servo motors in place The “1” after each item indicates that the item has completed
once everything is working. However, we need to be able to return successfully. A “0” indicates that a failure has occurred, and that
ours to original condition, so have just used some double-sided command is where your troubleshooting should begin.
3 4
Tap on the new connection, and it should try to connect. If you don’t
see the “Connected to…” message, then check you are connected to
the WiFi network. Tap on the “Publish” tab, then the + symbol. You
can use the “Subscribe” tab to monitor messages, but any topics
under the “Publish” tab are also subscribed, so it’s easier to just
have them on one tab. Tap on “Switch” and enter the parameters
[4]. Tap “Save’, and you should see the following [5] (except for the
two buttons, which I’ve added).
Now tap the switch, and you should see the Arduino respond. If you
have a console open with the subscribe command, you should see
the messages showing there as well. If you don’t have an Android
device, then there are other options such as using the command
line, or even using another Arduino as the controller.
WHERE TO NEXT?
MQTT
›› Based around a single broker, it is possible to create a network
of sensors and actuators to create an automation network. A
temperature sensor can read an analog value and report it to the
Broker
broker, while an app can be used to set a setpoint. An Arduino
based subscriber can compare the temperature reading and
setpoint and decide whether a heater should be on or off. The app
can also report the reading from the temperature sensor via its
Installation
subscribe tab, and if the Arduino can report the heater status back
to the broker, this can be viewed in the app as well.
To add extra “responses” into the Arduino code, look for the
following code in the dotopics() function, and add them below:
If you want to publish data to the broker, there is a function The first line updates the package list with the latest versions.
WIFIsendpub() which can be used for this. For example, another The process can take a few minutes or up to half-an-hour on a
Arduino on the network can have a push button, which has the newly created image. The second command should run quite
effect of remotely operating the lightswitch: quickly. The end of the output should look something like this:
if(onbuttonpressed()){
WIFIsendpub(“lightswitch”,”on”);
}
WANT MORE?
To grab the code or leave a comment, visit:
https://diyode.io/003dcvt
The version numbers might be different, but everything should be Another way to test that the service is running correctly under
fine if you don’t get any error messages. I found the service was Windows is to run the command “netstat –an” from a command
set up to run by default, which is necessary for the broker to be prompt to check that there is a TCP service running on port 1883
available after a reboot. The https://mosquitto.org/download/ page (the MQTT default).
lists some basic instructions for other Linux distributions.
Download http://slproweb.com/download/Win32OpenSSL_Light-
1_0_2L.exe from http://slproweb.com/products/Win32OpenSSL.
html and install it using the default settings. Also download ftp://
sources.redhat.com/pub/pthreads-win32/dll-latest/dll/x86/
pthreadVC2.dll, and note where the file is saved.
For my version of the MQTT Light Switch project, I’ve got it set up to
Then download and run the Windows mosquitto installer from run on an OpenWRT router (an Arduino Yun), and this was simply a
https://mosquitto.org/download/. The installer will probably case of running these two commands to install:
error when it tries to run mosquitto for the first time. Copy the
pthreadVC2.dll file to the mosquitto folder (C:\Program Files (x86)\
mosquitto on my system), so that it looks like this: opkg update
opkg install mosquitto mosquitto-client
RIGHT ►
This version of K9 is down-
scaled from the last one.
BELOW ▼
K9's Bluetooth collar.
You Might
Recognise Him...
MAN'S BEST
ROBO-FRIEND
Taken as a likeness from the show-featured K9, this replica is
FERGUS HAINES impressive and interactive. We caught up with Fergus, its maker, to
Aircraft maintenance engineer and sci-fi see what went into making this awesome replica.
robotics enthusiast, from Sydney, AU.
www.youtube.com/user/R2D2inAustralia Your replica K9 robot is great - are you a big Dr Who fan?
Dr Who really only got my attention when Billie Piper and David
K9 has been a favourite in the cult hit Doctor Who. Tennant were in it. My interest grew when I saw K9 and Cybermen in
Fergus has built many robot replicas, and this is his other episodes. I may have also painted a sliding door as a TARDIS...
second K9 replica. It's a labour of love. purely from boredom, of course!
What was your original intention with K9 - just a bit of fun, or was it
to serve a specific purpose?
Whilst building the mini K9 I was invited by Jaycar to bring my I don’t use CAD or CNC and therefore there are a number of
Replica R2D2 to their Oz ComicCon stand in Sydney, and collect parts that were remade during the project. Fitting servos in
donations for the Westmead Children’s hospital. This made me confined spaces resulted in access and functional challenges
reevaluate my K9 build criteria. I opted to use as much hardware during the build. The biggest collection of “spare parts” are from
that would be available in their Arduino stock, to demonstrate redesigned tail mechanism pieces that had to be assembled
its practicality. I had seen various toys with interactive platforms in a specific order, along with the first head frame that simply
and a commercially built mini R/C K9, which had little or no couldn’t contain functional mechanisms.
functionality.
There’s nothing like having a robot too big for your car to cause
you to rethink your plans! Since your K9 is much more than just a
radio controlled dog robot, tell us a little about K9’s capabilities.
Designing the shell by hand. Fitting the electronics to the smaller chassis was a challenge.
›› That’s some excellent battery life! Tell us about the touchscreen; There’s nothing like a deadline to make things happen (we know a
what functions does it perform? thing or two about deadlines too!). If you had your time again and
were looking to build K9 version 3.0, what would you change?
The 4D systems module has been programmed to display
animations and select Arduino sketches to control K9 ear and tail I would put more distance between the two tank drive mode wheels
movements. Two servos combined, operate the tail mechanism, and the rear caster, as it’s currently very sensitive with the Bluetooth
two servos for the individual dog ears, one servo for the extendable app. This could be easily changed to standard R/C setup, but it
“laser” nose gun, a drive motor controller board, 14 panel LEDs, would have less Arduino functionality as a result.
and two Jumbo LED eyes. The main switch is a three position switch
where one selection provides full functionality, the other offers That’s true. An R/C robot dog is still cool, but not really what you set
full controls but no drive motor availability. This was to ensure no out to achieve. What are you working on now?
accidental movement whilst on a display counter.
I have a number of projects to complete and others to start. My
On boot-up, the 4D systems screen displays Dr Who images from full size scratch-build Star Wars chopper Droid needs its drive train
Google, which are preloaded into its microSD card. Once up and “refined” for more reliability and stability. I may even work on the
running, pressing the front of the screen allows a sub menu for the mini K9 ticker tape printer that I originally intended to include in its
head controls to be selected. Four selections are displayed for the build. I also have to do some maintenance and repairs on my R2D2
ears: scan, patrol, normal and stop. Part of this sequencing sees the for a “Make A Wish” event.
nose gun extend and the laser (LED) illuminate, then retract. The
screen reverts to displayed images that change as per programmed Wow - sounds like you have quite a number of projects on the go,
timing. Touching the screen again brings you back to the menu. and for a great cause too! Be sure to let us know when your next
Touching the screen again selects the tail mechanism functions. It one is complete. Thanks for taking us through your K9 replica! ■
was decided to name them Rotate, Wiggle, Waggle and Stop.
GOT SOMETHING TO SAY?
Autonomous self-drive and object avoidance could be an upgrade To discuss this feature, visit:
with a future expansion. https://diyode.io/003tfrf
We love the “nose laser”, it’s very cool! The entire build has been
well thought out with some very complex servo configurations,
even if it’s just for comedic effect. What unexpected challenges did
you face while creating K9?
ARRAYS
AND
LOOPS
Last month we looked at data types with
variables. But what if we have a group
of values that we want to store? That’s
what arrays are for. - by Oliver Higgins
As we progress in programming, we are quickly presented with the If we look back on a variable being a container that we can store
daunting task of repetition and how to deal with it. After all, this is items in, the array is a collection, group or list of those containers.
what computers are good at. In this article, we will discuss loops For example, we can have six objects that are the same containers
and arrays. Working with both of these we can automate many but hold different colours [1]. The array gives us the opportunity to
tedious and complicated tasks. So what comes first? The loop or simply tell the code which index our item is located in, and it will
the array? Depending on the loop, you need an array, and the best return that very item.
way to go through an array is with a loop - so the answer is both,
concurrently. However, due to the our human inability to multi-task
1
and read two columns at the same time, we will look at arrays first.
We would recommend reading this article then re-reading it again, ARRAY
as the two subjects are intertwined.
with B variable, and then returns the result. We now have a third int x1 = 0
number that we can output to the user. However, once your program int x2 = 0
becomes more complex, you will find that you will have similar int x3 = 0
types of data, or a lot of data that relates to the same information; in int x4 = 0
which case, defining an individual variable each time you need one, int x5 = 0
However, we have to write it, access it, and every time we need to
make a change it must be rewritten again, which becomes a very
laborious task and one prone to user errors. What happens if there Arrays Versus
are 6 or 7 or 389,034 integers? It is impossible to maintain the code
and also, you may not know how many variables we’ll need until Many Variables
runtime. What if it’s dynamic and the number needed changes?
We want to be able to create a list of variables that we can move It’s important to remember that arrays are the most useful
through, which are as big or small as we need. This is where the when dealing with a group of data. For example, if you
array comes in. If we are to look at our previous declarations on the wanted to log what you did throughout the day, having an
six integers, we can do it much more efficiently using the following: “activities” array could be beneficial.
int x[6] // this will give us six elements, but activity[0] = "Ate breakfast"
remember the count starts at 0 and goes to 5 activity[1] = "Got dressed"
activity[2] = "Went to work"
Let’s take a closer look at this declaration. The first part is “int”. We
are declaring a variable of type integer. Remember that all elements This make sense, because all items are related since they’re
of the array must be of the same type; we cannot store a number in all actions being taken throughout the day. If you need to
one element and a string in another. The next is the variable name, output the data at some point, you know it’s all related to
in this case, “x”. Finally, we have square brackets with a number in some sort of collection of data. Arrays are less useful when
it. storing unrelated data such as:
You can see how the last array is very difficult to do anything
This will give us the first element in the array. Remember, with, due to the nonsensical nature of the data. When storing
programmers start counting at 0, not 1. To access any element, we a series of unrelated items, it's usually more feasible to store
require, we just change the number: them as individual variables, such as the code below.
This will give us the fourth element in the array. Now at this point, int birthYear = 1950
you will be forgiven for asking, “what difference does that have to
the original set of variables we made?”. We still have to write down
which one we want to access; so you are right, kind of; this is the Declaring variables like this for each piece of data is OK when
segue we need to look at loops. you have a fixed number of variables. If you need flexibility in
your data storage then this might not help either.
What if we could tell the system that we wanted it to do the same
thing over and over again? How do we inform the system of what we Of course, this month we’re dealing with standard arrays
need to be done, and how does it know where it is up to? This is the called “indexed” arrays. In future we’ll explore “associative”
marriage between arrays and loops. For example, let’s say we have arrays, which can be useful when storing less cohesive sets
a class of 15 students and we need to store their final grades. We of data due to their descriptive nature. While some languages
will be using the whole number, so we need to declare an array of create and use associative arrays the same way as indexed
integers to do this. ›› arrays, they aren’t simple to deal with in all languages, so
we’ll cover them another time.
the same type. You can mix in integers with strings and other data shopping list then
ARDUINO CODE: We use this when we have a required number of loops to complete,
and we “know” how many times we need it to execute in order
to achieve our task. This is probably one of the most commonly
char* shoppingList[]={“potatoes”, “tomatoes”, used loops and is extremely versatile. In the context of the array, we
“beans”}; know how many elements that are in it, through either the original
void setup(){ declarations or by accessing the number of elements.
Serial.begin(9600);
}
void loop(){ int size=sizeof(arr)
for (int i = 0; i < 3; i++){
Serial.print(“Current item : “);
Serial.println(shoppingList[i]); The basic anatomy of a For loop is:
delay(500);
}
} for x = 0 to 5{
do something each time
}
LOOPS statement 2;
etc
Loops are fundamental to making your coding life that much better. etc
We have three main loops that we use when we need the system to }
do repetitive tasks. The For loop, the Do loop (or Do While), and the
While loop.
The above code is a more robust example.
THE “FOR LOOP”
Variable initialisation is the initialisation of the counter of the loop.
FOR LOOP
This is the declaration and instantiation of the varible that we will
use in the loop.
//Arduino code
FALSE
for(int x=0; x<100; x++){
Serial.println(x);
}
›› The below code will create and fill the student array we used THE “DO WHILE” LOOP
before, then use a For loop to access the student array:
DO WHILE
// Arduino code
int studentGrade[4]; // This will give us an
// array of integers to
CODE
// store grades in.
int i;
void setup() {
Serial.begin(9600);
// Enter the student grades here. Note we
TRUE
// declared an array of 4. CONDITION
// To access the array we use 0-3
studentGrade[0] = 81;
studentGrade[1] = 76; FALSE
studentGrade[2] = 84;
studentGrade[3] = 95;
} The Do While loop allows execution of statements inside the block of
void loop() { the loop, for at least one time, even if the condition in the loop fails.
for (i = 0; i < 4; i++) {
Serial.print(i); In simple English, we ask the system to “do” something “while”
Serial.print(“: “); something else is happening. We “do” it first, then we check if the
Serial.println(studentGrade[i]); variable meets the criteria for the “while”, and repeat or terminate
delay(100); accordingly. Basic syntax to use the Do While loop is:
}
delay(10000);
} variable initialisation;
do {
statement 1;
This example comes from the Arduino guide on For loops, and is a } while (condition)
Note: you will need to connect an LED to pin 10 as PWM is not Variable initialisation is the initialisation of the counter of the
available on the in-built LED. loop, before the start of the Do While loop. Condition is any logical
condition that controls the number of times the loop statements are
executed. Note: Iteration/increment is the increment/decrement of
// Arduino code LED Dimmer the counter.
int PWMpin = 10; // LED in series with 470 ohm
// resistor on pin 10 THE “WHILE” LOOP
void setup() {
// no setup needed WHILE LOOP
}
void loop() { CODE
for (int i=0; i <= 255; i++){
analogWrite(PWMpin, i);
delay(10);
} TRUE
CONDITION
}
FALSE
This is another loop like the Do While loop, in C. The While loop to suddenly terminate the loop, mid-loop, and return to program
allows execution of statements inside block of loop only if condition flow. How does this differ from the While and the Do While loops?
in loop succeeds. Please note that compared to the Do While loop The simplest answer would be exceptions. The code may execute
the condition check here occurs BEFORE the execution of the code. intention as described using your loop, but there may be a situation
This way you may check the conditions and avoid executing code at where the system has an interrupt or emergency protocol. Your loop
may check this with an If statement, and then break the loop mid-
execution to limit damaging the system.
variable initialisation;
do {
while (condition) { variable initialization;
statement 1; while (condition to control loop) {
statement 2; statement 1;
iteration of variable; statement 2;
} if (condition outside of loop == true) {
BREAK
}
}
all if required. Note: Iteration/increment is the increment/decrement
of the counter.
NESTED LOOPS There you have it! Loops and arrays will make your code more
flexible, and allows you to do more with less code. ■
These three loops will provide the bulk of the pragmatical iterations
you will need. However, if something does not meet your needs, NEXT MONTH:
you can always nest loops. So your loops can have loops, which can MUTLI-DIMENSIONAL ARRAYS AND FUNCTIONS
have loops!
GOT SOMETHING TO SAY?
BREAKS: Loops have controls structures within them, and the To discuss this edition of Secret Code, visit:
most common are called breaks. The break is used when you need https://diyode.io/003nxks
SHARE.
INCREDIBLE
PROJECT
RED LASER
Everything you
need to drive
4
$ 95 $1995 $ 2995
the laser diode ADD AN INTERFACE TOUCH CONTROL
is included on 2 x 16 LCD Mono LCD with backlight. Colour resistive touch LCD display shield. Piggy-
the board. 5V. Text only. 6 input buttons. XC-4454 backs straight onto your UNO or MEGA.
XC-4490 240x320. XC-4630
FROM
$
14 95 9
$ 95
5 ea
$ 95
4
$ 95
UNO
The classic UNO offers the best shield compatibility, especially
if you are working with a shield that uses SPI (serial peripheral
interface) for communication. Most shields are designed with
$
2995
the UNO in mind, so if you’re having trouble getting sample code
working, making sure it works with an UNO is a good start. XC-4410
NANO LEONARDO
If you have a design you need to make
smaller, or just want something compact to
$ 29 95 The big difference between an UNO and
a LEONARDO is the microcontroller
$ 2995
fit on a breadboard or prototyping board, IC on the LEONARDO has the USB
then the NANO is a good choice. Because functions built-in. While this saves
the NANO uses the same microcontroller IC an IC on the board, it also means
as the UNO, practically any circuit designed the microcontroller can talk
around an UNO can be transferred to a directly to a connected computer
NANO. XC-4414 via USB. XC-4430
LILYPAD USB
The LILYPAD USB is designed MEGA
around a 3.3V board voltage, so You will need a MEGA if you run out
should be considered if you are of resources - whether it is pins,
interfacing to modules that are RAM, EEPROM or program flash
not 5V tolerant. The LILYPAD memory, the MEGA has more of it.
USB also has an inbuilt Lithium Even if you need extra hardware
battery charge circuit, so is serial ports or PWM capable
ideal for projects that will need
to connect to a battery.
$ 2995
pins, these are available on
the MEGA. XC-4420
$ 4995
XC-4620
This is SAM.
Sure, a robot that cooks you dinner or can walk the dog is great, but
before our robotics skills can run, they must walk (or indeed, roll).
So let’s start with the basics and build the "Somewhat Autonomous
Machine", affectionately known as SAM. - by Oliver Higgins
In the maker space, there’s not a lot cooler than robotics, but if as my original design just without the tank tracks, or the flame
you’re just starting out where do you even begin? Robotics is a very thrower, or the path of destruction for other robots. What we did
broad term; traditional sci-fi has us envision bi-pedal android type agree on was the need to create an initial platform that could serve
robots that can be easily confused with humans, but the reality is as a base for understanding the fundamentals of robotics.
that a robot can be a very simple machine. A true robot, in fact, is
anything your imagination can envision. The truth is that robots are designed to do tasks that we do not
want to do, to go where we cannot, or operate in environments that
The boss here at DIYODE Magazine said we needed a robot. I agreed present danger. They are designed to be as efficient and productive
and so produced my plans for an epic, tank track-driven, flame- as possible in doing that designated task. For our robot the task
throwing robot destined to destroy all other robots in its path. We here is simple: roam around the room and don’t hit the walls, chairs,
discussed it and came to a compromise. It would be the same robot feet or the dog.
Fundamentally any robot exists as a system. The system is a THE BROAD OVERVIEW
set of inputs and outputs with a decision making process in the
middle. Arguably you could set your robot on a predefined pathway This robot is quite simple but still requires some pre-planning. Upon
assuming nothing will go outside of your control. However, this power up the robot will drive itself forward. It does this by switching
could very easily end in a result that could damage your robot or both sets of drive motors in a particular direction. As the code
yourself (the author was attacked several times during the making loops, it uses the ultrasonic sensor to send out a pulse to which
of this article due to a preprogrammed robot that was having new it measures the distance of any object in front. Once an object is
code uploaded on the workbench, which lurched it into action). We detected, it stops the robot and enters a conditional section of code
need to ensure that we have a series of feedback loops in place to that sends it in the opposite direction, then manoeuvres to switch its
be sure that the task is carried out correctly. direction. Once complete it reverts to the original routine and moves
in a forward direction until it encounters another obstacle.
INPUTS
HOW IT WORKS
Any system or robot will require various inputs to be evaluated
before making decisions. Inputs can be simple or advanced, from THE UNO BRAIN: In this instance, the Arduino UNO is our
pressure, air speed, temperature, angle, G-force or anything else microprocessor of choice, as it is a simple, open source and a low-
you can measure. In this case, we are using distance as our input cost microprocessor. It also has the power required for many of our
metric. We could archive this through several means, but we will be functions.
using a cost-effective and easily obtainable ultrasonic transducer.
ULTRASONIC DISTANCE SENSOR: Our input device for this build is
PROCESS the HC-SR04 Ultrasonic module. This is one of the most simple and
cost-effective methods for measuring distance; however, it comes
The robot needs a brain; it needs to be able to take the information with some caveats. The Ultrasonic works by sending out a timed
from the inputs, evaluate it and then perform an action of outputs, soundwave well beyond what the human ear can hear. If there is an
based upon that decision. This could be as simple as a yes/no logic, object in front of the sound wave, it is reflected off the object. This
such as “do X until Y happens, then stop” or it could be a much more bounceback is received by the unit and the time taken for this to
complex fuzzy logic system that will make various decisions based occur is then calculated using the speed of sound, to work out how
on several inputs or system states. far away the object is. ››
OUTPUT
As you can see from the diagram on the right, the system follows
SETUP
a very simple strategy for obstacle avoidance. This is designed to
provide very simple functionality to demonstrate the principles in
this project. However they're very "yes or no" binary decisions.
What we have described here are feedback loops. Anything that OBJECT
goes out must come back. Feedback loops serve to give us constant DETECTED
evaluation and defined processes. Traditional logic is very concrete. PING
States only exist as true or false, high or low, 0 or 1; but fuzzy logic SONAR STOP ALL
concerns itself with degrees of truth. For example, how do we BACKWARDS
STOP ALL
define tall or short? It could be as simple as “if something is bigger TURN LEFT
than a certain number, then it is tall”. But tall will be relative to what NO
is short, within a defined pattern set. We need to understand the OBJECT
natural environment that our robot exists in and determine how it
should react given a set of inputs.
FORWARD
›› So how do we calculate the distance? The speed of sound is L298N MOTOR CONTROLLER
0.034cm/µs or 340m/s so if the object is 10cm away it will take
294microseconds. However, what you get back from the echo pin For this project, we will be using the L298N Dual H Bridge package.
will be double that number, due to the time it takes for the sound In this instance, it is the duinotech, XC4492, which is an inexpensive
wave to return to the unit. To get the distance in centimetres, we module that makes utilisation incredibly simple. It operates as a
need to multiply the received travel time value from the echo pin by two-channel device, which can let us operate the left and right
0.034 and then divide it by 2. By using this calculation against the pairs of motors. You can easily use two or four motors. There are
known speed of sound, we effectively gain a distance measurement. versions of the L298N modules that have two chips allowing you
to create four channels; in the case of our robot this would enable
PROBLEMS: The Ultrasonic modules work well when you have a independent four wheel drive. However, for our current purpose this
large surface to reflect off, and the unit is perpendicular to the would be overkill, so we will use two channels and enable skid-steer
object. If the object is smaller, it will need to be closer before the or tank track-style direction changes.
sound wave will reflect and can be calculated correctly. If the unit is
at an angle, then the reflection does not bounce back at all, and it The L298N works by sending a PWM signal (from 0-255) to the
will often require the robot to be incredibly close before it receives enable pin of the channel you are using. It then specifies the
the information it requires to calculate the distance. [1] direction required by sending the two other pins high, low or a
combination of both. This is repeated for the second channel, thus
requiring six outputs from the UNO to control the motors.
1
On top of the standard VCC and ground, the L298N has a second
voltage input VMS, which is used to supply the power for the
Trig 10µs Trigger
motors. Each channel requires three inputs: the ENA and the IN1 &
IN2 in the case of motor A.
MOTOR OUTPUTS: This project could easily be built with two or four
motors driving the unit. The 4WD is not truly independent; it could
8 Cycle Sonic Burst be achieved by using a four-channel motor driver, then providing
a sensor on each wheel for detecting slippage. Power could be
removed or decreased to that wheel and apply more power to other
wheels.
For this build, we will be using basic DC hobby motors. Each motor
is driven by the control module with simple DC. They are connected
to a small plastic gear box, which is connected to each wheel.
THE BUILD
Using jumpers connect the following from the UNO to the L298N.
Connect the other GND to the ground on the L298N board.
THE 3D PRINTABLE BRACKET The system will power up on as little as 6V; however, we would not
recommend it. During testing, we found that once the power was
The 4-wheel chassis you're using may not be the same of ours, applied to the motors, the board logic would become erratic and
or you may build your own entirely. For this reason, we created a inconsistent. Applying 12V (8xAA) solved all these issues instantly. ››
simple 3D-printable caddy. This caddy holds the Arduino UNO and
motor controller so there's no strain on the wiring. Since there's
2
not really much strain on any components here, you can simple use
double-sided tape to mount the caddy to the 4-wheel chassis.
We have provided the .stl file for 3D printing in the digital resources
along with the code. Feel free to modify this however you like. It's
very likely that Part 2 of this system will have a very different caddy
too, to support whatever system we add next.
›› If your L298N board has the 5V_EN jumper I would recommend THE CODE
removing it while connecting power. This will essentially disable the
motor outputs. Connect your GND wire from the power source to the The code is quite simple. Once compiled it should be ready to go.
GND screw terminal pin on the L298N board. Then connect positive We have provided you with sam_v1.ino in the digital resources. Load
power to the VMS terminal; you will also need to connect this power the sketch onto your UNO board.
to the Vin on the UNO. The unit should power up if you removed the
5V_EN jumper then reconnect it - but be warned; the motors will While you don't really need to know precisely what we're doing in
power up straight away! the code, our goal with SAM is to help you understand precisely
what's happening. For that reason, we'll take you through some of
It would be quite simple to add a small switch to the enable pins on the important parts of the code. Understanding the code will also
the motor controller, or inline with the power supply to the Arduino. help you with debugging should your SAM not work perfectly first
Either would make it easy to halt all movement. go, as most pins are explicitely noted in the code too.
Firstly we need to set up the input and output required, for the
ultrasonic sensor and the motor driver. The only variables you need
to change are ob_distance, which is the distance at which the robot
will stop and turn. The next is motorSpeed. This is a value of 0-255,
with 0 being 0% and 255 being 100%. This will be dependent on
your power and motors, so be sure to adjust as required.
Next is the setup routine. This sets up the motor driver channels and
the ultrasonics pins for input and output.
void setup() {
pinMode(ENA, OUTPUT); //Set all the L298n Pin
to output
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(trigPin, OUTPUT); // trigPin as output
pinMode(echoPin, INPUT); // echoPin as input
}
Next, we have a series of functions that the loop will run to make the
system work. Firstly we have the code required to run the ultrasonic void loop()
the distance in centimetres to the object detected. This works by if (pingSonar() < ob_distance) {
pulsing the trigPin then reading the echoPin. This returns a long stop_all();
divide by 2, allowing for the round trip (since we're reading the echo backward();
Finally, we have the main loop code. In this case, we have made it as analogWrite(ENA, y);
simple as possible using only a single if statement. Once the robot is analogWrite(ENB, y);
POWER
JASON GREENLOW
Mechanic and lifelong gadget enthusiast
living in Perth, from Christchurch, NZ.
@jason.greenlow
The inverter pr
ovides plenty
of mains pow
er.
Jason created his own Lithium Ion powered portable
power supply. Using old laptop Lithium Ion (Li-ion) batteries and
some Aussie ingenuity, he’s created a portable power bank in an
ESKY, which arguably is better than having a few cold beers inside!
We’ve seen cooler boxes converted to powered cooling units, I’m normally a rush to the finish line sort of fella. I want my project
but haven’t seen too many power banks! What was the lightbulb done now or yesterday, but I actually took my time with this one. I
moment that made you start this project? looked at the cost of all my parts first, to find the cheapest options
available, knowing that the most expensive part would be finding
It was a mixture of things. I had about 300 Li-ion cells lying around a cheap pure sine wave 24V-240V inverter. I built my Li-ion battery
from old laptop batteries which I had stripped and tested each pack to be 24V with a BMS (battery monitoring system).
cell. One day there was a power cut, which lasted for a few hours,
I thought I’ll give the generator a run but then on the other hand, Being a mobile device I wanted to get as much punch out of the
it’s loud and I like my neighbours. So then I thought, wouldn’t it be battery pack without getting too heavy; this also meant that I could
great to have a mobile power supply? get more time out of the inverter. Well, the theory was: the less load
on the battery pack from the inverter, the more battery time I would
Oh yes - the dreaded extended power outage. We’ve experienced a get. I built my own DC-DC converter to run the 12V system because I
few of those ourselves. Did you set about designing it first, or wing couldn’t find a 24-12V 30A converter anywhere; but it was also nice
it and see where you ended up? knowing that 70% of the project was built by me.
Low current DC-DC converters are readily available, but high current That’s VERY fast recharging! If you had your time again, would you
converters are hard to come by. We wondered if the conversion to change anything?
12V for low-voltage devices would offset any improvement from a
24V system, but there are many variables. What made you decide to If I was to change anything, I would find or make my own storage
build it into an ESKY? unit instead of an ESKY. One extra component I’d like to install is a
battery bar meter, so I can easily see the battery’s state of charge.
I used an ESKY for a few reasons. The first was because it provided
an insulator around the electrical components, so it meant there Well, it would save you buying another ESKY for beers, but it did
were two layers to get through in order for anything to be damaged turn out really well! What are you working on now?
due to impact. The second was the cost of an ESKY; compared to a
typical junction box of the same size, the price difference was huge! Currently I am thinking about building a device for drivers that
And the ESKY comes with a free handle! prevents falling asleep at the wheel. I’ve not started anything yet;
it’s more of a brainwave at the moment but the device involves blue
To be able to use a 12V solar panel or to charge the battery pack via light theory.
12V anything, I've used a 12V-24V boost converter to charge, and to
create a stable charging input. The boost converter is set to boost to Sounds great! Be sure to update us when you get that one in the
25V and the BMS manages a balance charge. works! ■
Integrating battery management for flexible recharging is a great GOT SOMETHING TO SAY?
idea. How fast can you recharge the battery? To discuss this feature, visit:
https://diyode.io/003cwjd
The BMS controls a balance charge, cuts the power off at 22.5V
minimum voltage output, cuts charging off at 24.4V, and has an
output current rating of 50A. It also has overload protection. So far a
full charge takes about 1.5 hours.
RESISTORS
AND HOW TO
USE THEM
This month in The Classroom, we’ll take a
break from absolute theory and instead look at
something students and makers alike need to
understand: identifying and correctly using some
basic electronic components. - by Daniel Koch
Resistors are components designed to resist the flow of electricity, There are other sizes, and types of resistors around. Resistors rated
thereby reducing current flow, limiting voltage, or generating heat, at 1W or even 2W look a lot like a larger version of a 0.5W type, but
often very precisely. Resistors are literally meant to get in the way, can dissipate more heat. The 5W, 10W and 20W resistors, as found
but only a little bit. The measurement of that resistance (i.e. the at your electronics store, are of a construction called wire wound,
“value” of a resistor) is given in Ohms, which is symbolised using Ω. ceramic case. These are “Power Resistors” made with fine wire that
In Australia, the circuit symbol for a resistor is a rectangle with the is wound around a ceramic former, coated in ceramic compound,
value next to it or in it, always given in Ohms. Previously, the symbol and embedded in a rectangular ceramic carrier, which both protects
for a resistor was a zig-zag line. You will often still find it in current the resistance and dissipates heat.
literature too.
Resistors are typically made in set values. You may have heard of the
E12 series or the like. This means that for each power of 10, there
are 12 values of resistor. So from the range 10Ω to 100Ω, there will
be 12 values: 10Ω, 12Ω, 15Ω, 18Ω, 22Ω, 27Ω, 33Ω, 39Ω, 47Ω, 56Ω,
68Ω, 82Ω. For the next power of 10 – being 100Ω to 1000Ω – there
will be another 10 values, basically the same numbers but ten times
greater.
When you’re looking at a parts list, the next number you’ll typically Whenever an engineer designs a part, as well as other dimensions,
see in a resistor name is a power value in watts. In real terms, this that part will have the tolerances specified. In many industries,
means the amount of power that a resistor can turn into heat before this will be a range of acceptable sizes or other dimensions.
becoming physically damaged. Many of the resistors in educational Typically parts will be given a ‘Nominal’ value, perhaps in metres or
kits, experimenter’s kits, and on Arduino and Raspberry Pi boards millimetres, and a ‘Tolerance’ in millimetres or even micrometres.
are 0.25W or 0.5W sized. You may have 1/8th Watt, (0.125W) in very
small or even SMD resistors, but again won’t usually buy them for a For example in an Aluminium extrusion factory I used to work in,
project. Aluminium tubes were cut to 3.6m +/- 2mm. I had to ensure that
each each tube was between 3598mm and 3602mm.
Interestingly, even though 0.5W dissipate twice the heat of the
0.25W, they are both the same size due to how they are made. Although resistors have physical dimensions and tolerances,
0.25W resistors are usually carbon film types. That is, they are a the important tolerance is of the actual resistance. Unavoidable
film of carbon around a ceramic former, with a metal cup and leg differences exist in any batch of material, so although a precisely
attached at each end. The resistor is covered in a protective coating calculated and applied layer of metal film is deposited on the
of a colour that reflects the technology used. The coating carries ceramic, and then laser cut, or trimmed, the exact resistance will be
information about the resistor via colour coded bands. between the two values of tolerance, the upper tolerance, and the
lower tolerance.
In contrast, 0.5W resistors are usually made with a metal film on the
ceramic core, which can handle more heat for its size than carbon Electronic component manufacturers work in percentages for their
film. Metal film resistors are the most common today, after carbon tolerances. Commonly, metal film resistors have a tolerance of +/-
film. 1%, while carbon film resistors often have a value of +/- 5%. ››
›› This means that a given metal film resistor may be lower or higher For numbers between 1,000Ω and 1,000,000Ω, the decimal
than its stated value, by an amount of up to one per cent of that multiplier “K” is used. This is also often abbreviated in speech
value. In real terms, a 100Ω resistor may be up to 1%, or 1Ω, higher as just “K”, for Kilo-ohms, which is often called “Kilohms” with a
or lower, making it potentially anywhere between 99Ω and 101Ω. single “Oh” sound. Grammar fanatics like the primary teacher in me
struggle with this, but as it is a piece of jargon or metalanguage,
Tolerance values are written on resistors with a tolerance of better absolute grammar rules do not apply.
than 20%, as the fourth or fifth band on a resistor, depending on
the type. Colour banding is discussed below. Some applications For numbers one million Ohms or more, the letter “M” is used, for
allow a wide range of tolerances without a significant issue, but “Mega-ohm”, which is often pronounced “megohm” and simply
others require a high level of accuracy, i.e. a low tolerance for error. abbreviated to “Meg”. For many of us, these letters are familiar from
Electronic Instrumentation for example becomes less accurate with day-to-day life, being standard Metric terms.
badly chosen values of resistance.
As an exercise, teachers should collect a number of 5W to 20W
KNOWING VERSUS FINDING resistors, or find some in an old TV or such, and compare the
markings. Decimal points get easily lost or confused with dirt and
The resistance, power rating, and tolerance of a resistor are stray marks. For this reason, a value of, say, 4.7Ω will often be
certainly the three main pieces of information needed for most of stamped as 4R7. Likewise, 4700 will be stamped as 4K7. Including
us to choose and use a resistor. Although not discussed here, some the multiplier as the decimal point creates clarity and removes
resistors also show a temperature band, although not normally doubt, and reduces the number of characters to be printed, but can
required for hobbyists. confuse new users.
So, how does one find this information on the actual resistor? In the Tolerance is stamped with a single letter code, and unfortunately,
case of power dissipation, this is basically indicated by size, but the while there are industry standards, in my experience, manufacturers
background colour defines the type of technology in the resistor. may apply their own rules.
Carbon Compound Resistors had a brown body, but were rated at
several power levels and poor tolerances. Carbon Film have a cream Generally, you will find they are labelled “K” for 10%, “J” for 5%, “G”
body and also come in different power levels, Metal Film are often for 2% and “F” for 1%. There is a problem here though, as K is used
blue, and so on. as both the decimal 1000 multiplier, and the common tolerance
of 10%. So care is needed here, although thankfully, the tolerance
Knowing the technology therefore helps find the power dissipation letter is usually all by itself, away from other letters and numbers,
levels, but, if you are purchasing new components, then that and nearer the edge of the component.
information will be included in the packaging or the catalogue, or
the manufacturers data sheet. Often, a project or kit comes with TWO OF THREE
metal film resistors, and when one is lost or damaged in assembly,
a common mistake is to replace it with the same value carbon film The second textual system is also used on larger format resistors,
type. Remember carbon film (cream) are half the power rating of and usually on surface mount devices. This system consists of three
Metal Film (blue). numbers and a letter. The letter is the same tolerance indicator as
above, making that one fairly easy, as long as you do not mistake the
Resistors of 5W and above actually have the dissipation stamped ‘K’ for kilohms.
on them, although size is a fair guide too. You will quickly come to
recognise what is normally a 5W, 10W or 20W Ceramic Block Wire The three numbers are not as complicated as they look. What you
Wound Resistor. are looking at is two significant figures and an exponential number,
or multiplier. Think of it as a simplified scientific number. The
There are three common systems that manufacturers use to detail multiplier is literally the number of zeros that follow after the two
the value and tolerance information for resistors. As stated above, significant figures.
at the 5W mark and above, resistors are large enough and made
of a suitable material and shape to have the information stamped For example, a marking of ‘152’ is the same as 1500 Ohms, where
or printed on them. The value may be written as a number, such 1 and 5 are the significant figures, which are 2 place values (or
as 100Ω, but this is less common. Instead, a decimal multiplier 2 zero's) away from the decimal point. Likewise, 473 is actually
system is usually used. Two are common: the first is the same 47,000Ω or 47kΩ. In all cases, the number will be in ohms when
decimal system we are familiar with from weight, volume, and mass expanded with all the zeros. There are some challenges with this
measurement. That is, below 1000, resistance is simply printed system for smaller values. In fact, I have only seen it used recently
straight on the resistor with the letter “R” after it. This is because on variable resistors, but more about these soon.
the symbol for Ω often looks far too similar to a “0”.
BLACK 0 0 0 1
BROWN 1 1 1 10 1%
RED 2 2 2 100 2%
ORANGE 3 3 3 1000
YELLOW 4 4 4 10000
5 5 5 100000 0.5%
GREEN
6 6 6 1000000 0.25%
BLUE
7 7 7 10000000 0.10%
PURPLE
GREY 8 8 8 0.05%
WHITE 9 9 9
0.1 5% GOLD
So this is all well and good for the larger resistors, which are big The numbers grouped together are either two or three significant
enough to physically print numbers on, and for SMDs that use very figures, then a multiplier, and each coloured band represents a
good printing, but what about the simple resistors that most of us number [1].
use? Although some readers may measure every resistor on their
multi-meter, most readers will be familiar with the little coloured The first two in a three-band group indicate the value, and the third
bands seen on these resistors, and some can read them. is the number of decimal places. In a four-band group, you have
three significant figures and one multiplier. The multiplier works out
These coloured bands painted around the case may look random, to literally be the number of zeros you add after you figure out the
but there is a reason to them, and a formula to read them. What significant figures as in our second method above.
you should have is a total of four or five bands, (occasionally six)
with one being separated from the others by a larger gap. This is The band all on its own indicates tolerance, which is also identified
not always the case however, so be careful! If all is going according by its colour, which can be helpful if the spacing isn’t great.
to plan and you do have three or four bands, then a gap, then one
more, well your life is easier! Read it from one end, and if it doesn’t So for a five-band resistor with colour coded bands of brown, green,
make sense, and doesn’t appear to be a standard value, try reading black, red and brown, has significant figure values of 1, 5, and 0,
it from the other end. and a multiplier of 2. There is also a tolerance band ››
›› representing 1%. Therefore, the resistor will be 1, 5, 0, and two the carbon track, current must flow through more and more carbon
0s, equating to 15 000Ω 1% or 15k 1%. in order to reach the wiper. At around 270° of travel, the wiper
reaches the other end of the track. The current must pass through
A four-band resistor will only be 5% tolerance at best. So the same almost all of the carbon in order to reach the wiper. In this way, the
value, 15k will be 1,5,3, will have bands of brown green, orange, resistance between the wiper [2] and the pin at the other end varies
gold. There may not be a gap before the tolerance band, but as the from ~zero to the nominal resistance of the track.
tolerance will only be 5% (gold) or 10% (silver) they will be easily
recognised as the tolerance band. There are variations on this theme. Some variable resistors slide like
the volume control faders on a sound desk in a music space. Others
Values of resistor below 10 Ohms are uncommon but still required are built for operation through 90°, such as those in radio control
to be marked. For example a 1.2 Ohm resistor is 12 with a multiplier situations. Still others look like the regular 270° round variable
of 1/10. The appropriate multiplier code for that is a gold band. resistors but are wire-wound for increased power handling.
Similarly a 1/100 multiplier is represented by a silver band.
Yet another variation is the trimpot. These are smaller variable
Colour banding is the most common type of resistor marking that resistors, which are adjusted by a screwdriver or dedicated tool.
most of us will come across. They are used for “set and forget” applications, like adjusting upper
and lower limits of a larger range. Trimpots come in a variety of
CHANGING RESISTANCE forms from open frames with carbon film to 25-turn precision wire-
wound varieties.
There is a lot of information here; but wait, there’s more! It’s also
worth discussing a different type of resistor: the variable resistor. WHAT’S IN A NAME?
Many circuits use adjustable resistors, or variable resistors, to Many people think a variable resistor is called a “potentiometer” but
control volume, speed, brightness, and on/off thresholds. Variable this is not strictly true as the term potentiometer actually refers to a
resistors are typically rotary types that revolve about 270 degrees, voltage divider. Originally the Potentiometer was a piece of Science
but some are sliding types as used on Audio mixing desks. Yet Lab equipment to measure voltage in an experiment. A voltage is
others are multiple turn rotary or screw types. As with fixed applied to one end, current flows through the whole resistance and
resistors, the common variable resistors are only able to dissipate a exits somewhere into the circuit at the other end. The variable wiper
little heat, so they are often used to control a driving circuit. taps off the desired level of that signal, as a part voltage of the total,
for the circuit to use [3]. It is the application of a variable resistor
In their most common form, variable resistors feature a carbon film that determines its name; however, as most often we are connecting
deposited on a resin bonded paper base, which is held in a pressed them as potentiometers (or “pots” for short), most of us know them
steel frame, with a rotor shaft through the middle of a mounting by this name.
boss. The rotor is connected to a wiper, which touches and slides
along the carbon film. The ends of the film are connected to the
3 +5V
outer pins of the case, while the wiper is connected to a third
contact.
2
+5V +5V +5V
Wiper
Signal
A B C
Signal
Out
+5V
Current flows in one pin into the carbon track and out the wiper. At
the initial position there will be very little resistance and possibly a
direct contact with the pin, but as the wiper begins to move around
I=
R ÷ ÷
In the case of a potentiometer, having three terminals means that
I R
V
the current entering one terminal is divided between the other two R=
I
× R on the Right
terminals. The voltage on the wiper is always a value between the
values at either end pin. Most designs are calculated to have a V=IxR
current passing through the carbon track, that is ten to twenty times
the current at the wiper terminal, so the wiper current makes a
negligible difference to the voltage at the wiper position. For this reason, we need a resistance in series with the LED as a
current limiter. This resistance is correctly called a ‘Ballast Resistor’.
The circuit symbols for some variable resistors are shown here too. To calculate the ballast resistor value, we need to use Ohm’s Law.
You’ll see that the chief difference is the screw-adjust type versus If the supply is taken as 5V, and the LED terminal voltage when lit is
the fully variable, hand-adjusted type. specified as 2.3V, the voltage difference across the resister needs to
be 5 – 2.3 = 2.7V. The specified LED current is given as 30mA, which
WHAT DOES IT ALL MEAN? is 0.03A. Remember: We must always work in amps, volts, and
ohms, never their multiplied or divided versions such as “milli”.
Now that you can identify most resistors in both physical form and
circuit diagrams, it’s time to learn a bit about how to use them. As Using Ohm’s Law to calculate the resistance or our resistor, we have
alluded to in the beginning of the article, resistors exist to oppose a voltage drop (desired) of 2.7V (V at the Very top of the triangle),
the flow of electricity. Those who have read previous editions may and the current (I - below left) 0.03A, i.e. underneath the 1.8V,
remember resistance as being like a smaller section of pipe that which looks like this:
slows water down; resistors are basically just that. You might want
to do this for timing reasons, or to reduce the current flowing 2.7 / 0.03 = 90 - This gives a result of 90Ω. The nearest standard
through a component to a safe level. E12 value is going to be 82Ω or 100Ω, which are both about the
same percentage difference, so we would normally use the higher
All resistors follow Ohm’s Law, which states that the voltage being value and accept a little lower light output.
dropped across the resistor (the potential difference existing across
it) is equal to the resistance of the component (in ohms) multiplied Let’s try again for the same LED, but running this time on a 12V
by the current flowing through it (in amps). It is important to convert supply. Now we need to drop (12V - 2.3V = 9.7V) at the same 0.03A.
milliamps (mA) to amps (A) before doing this though, as many
people struggle otherwise. 9.7 / 0.03 = 323.3 - In this case, the resistance is calculated as
323.3, which is again a non-standard value; so to run our 2.3V,
In any given circuit, where the 30mA LED on 12V, go to the next higher standard value of resistor,
which would be 330R.
voltage remains constant, the
current in such a circuit is directly There are many other reasons for using a resistor, although
unfortunately many are far beyond the scope of this article. Most are
proportional to the resistance of very situational, such as timer circuits where the resistor controls
that circuit. the charge rate of a capacitor to reach a threshold voltage to set a
flip-flop; however, that is worthy of a whole other article!
The easiest way to remember the formula is to draw it as a triangle Hopefully you have the knowledge now to identify the type,
[4] with V at the "Very top", and R on the "Right". That leaves only tolerance, and value of the resistors you are working with, and a
one place for I, which is the letter we use to represent current. basic understanding of how to safely use LEDs in your circuits.
Remember, the DIYODE classroom only exists as long as you
As a practical example, let’s take the common LED. LEDs are made continue to let us know what you want to learn about, so please
to emit light (we will cover PN junctions, diodes, and LEDs in future keep those topic suggestions coming in. ■
editions), and as such, they are not manufactured to be rugged. So
an LED that draws 30mA at 2.3V voltage drop would quickly burn GOT SOMETHING TO SAY?
out if connected to 5V. In fact, as an LED has no current limiting To discuss this edition of The Classroom, visit:
properties, it would burn out even if running on 2.3V with no resistor. https://diyode.io/003mxtb
Raspberry Pi
Network
Video Event
Recorder
Using a Raspberry Pi as an event-triggered video
recorder for IP camera streams, and the Raspberry
Pi camera. - by Rob Bell and Mike Lewis
IP surveillance cameras are powerful tools for security and THE BROAD OVERVIEW
monitoring. They’re easy to install, and can be wired hundreds of
metres away, even over WiFi. If you have a large installation, you There are various technologies being used here, and this system
probably had a large dedicated recording device to take care of the is a little more advanced than a basic RPi project. For that reason,
recording functions. But what if you only needed just one camera? there’s some more setup involved. There’s relatively little hardware
We will show you how. required to provide a working system. It should probably also be
noted that while we’re using RPi here, you could use just about any
The Raspberry Pi (RPi) is perfectly suited for this application. With single-board computer that you can install Ubuntu on. Even an old
it’s combined high quality processor and hardware interfacing via PC will do the job (but you may need to setup an Arduino or small
the GPIO, it enables you to record video as well as control recording device to handle hardware triggering).
remotely, via hardware interfacing. Sure, you could use the software
that came with your IP camera to do the same, but that’s not terribly HOW IT WORKS
efficient for your own computer, especially when it runs slowly as a
result, and you’re trying to do other work. There are several technologies being used all together, here. A
Raspberry Pi probably isn’t a new concept to you, so we’ll just cover
We can use open source software to read the video stream and save the ones that might not be familiar.
it to disk. The best thing is, using the GPIO interface on the RPi, you
can trigger recording easily from just about any hardware interface.
UBUNTU MATE: Ubuntu MATE leverages the power of Ubuntu, which NODE
SERVER
is an open-source Linux distribution, with the lightweight and
intuitive MATE desktop. While not specifically designed for RPi, they
LISTEN FOR
have a ready-to-roll disk image, so it installs almost as easily as INPUT
NOOBS does. Once installed it has full support for the RPi camera,
GPIO, all within a native Linux environment. It is possible to get our URL RECORD FOR
LISTENER X SECS
system here running on the default RPi operating system, but this is
just as easy to install and includes FFMPEG (more on that below).
GPIO
LISTENER
NODE.JS: Node.js is a powerful open-source, cross-platform
JavaScript run-time environment. It has seen a huge increase in IS GPIO PIN
popularity recently, allowing you to run JavaScript server-side, which ACTIVE
was traditionally used for web browsers client-side. What’s even
better about Node.js is there’s a fully functional library that provides
easy access to the GPIO. It also provides a web server engine to RECORD FOR
X SECS
serve pages quickly and efficiently.
RTSP: Most IP cameras, regardless of the brand name (or lack Once you have your bootable SD, put it into your RPi and power up
thereof), use a fairly standard protocol to transmit their video (connecting your monitor, keyboard, mouse, and internet). You won’t
stream over the network. This protocol is called RTSP, which is the need any peripherals later, but this makes life easier for setup.
Real Time Streaming Protocol (and yes, as with many acronyms,
people will often duplicate the last word and call it the “RTSP STEP 2: BOOT THE RPI AND COMPLETE SETUP
Protocol”, but we’ll forgive them for that).
Insert SD and power up your RPi with HDMI monitor, keyboard,
FFMPEG: This is an open source Linux distribution, which is included mouse and Ethernet (if required). Once Ubuntu MATE is loaded,
with Ubuntu MATE, so you don’t even have to install it. It’s the complete the setup [1], and connect it to the internet. If you
engine room of video handling for this process, and can be used download the resources for this project to your RPi, it will make
to do all sorts of grunt-work like converting one type of video to copying code files much simpler.
another, combining a sequence of images into a video, and more.
STEP 3: COMMAND LINE
SOFTWARE INSTALLATION
Access terminal so we can install the additional required libraries.
STEP 1: UBUNTU MATE You’ll find it in the menu under System Tools -> MATE Terminal.
This will allow you to easily install modules and packages to use
with Node.js. ››
Create a folder called /var/nodeapp/ and navigate to that folder. This With your text editor of choice, create a new file index.js (or copy our
will be our work directory. index.js file from the resources hello_world folder).
Create your Node app. The command below prompts you for a Type / copy / paste the following:
number of things, such as the name and version of your application.
For now you can simply hit “Return” to accept the defaults. We will
use the default entry point of index.js const express = require(‘express’);
const app = express();
This code may look a little strange but it’s the bare-bones of a Node.
This will add the dependency: express into your package.json file js web server. It basically loads required dependencies, tells the
and install the required files into the node_modules directory. Check server to respond with a “hello world” message, and to listen on
it has completed successfully with the following command: port 3000.
nodejs index.js
Hello World
2
To stop running the server, go back to the command line and press
Control + C.
json files as you won’t need them any longer. If you list out the -t 00:00:10.00 -vcodec copy -an /var/nodeapp/
contents of /var/nodeapp you should now see something like this: recordings/test.mp4
ubuntu@ubuntu-desktop:/var/nodeapp$ ls -1 In the above code, -t is the duration, this will record for 10 seconds,
/// the above command should list the which you can adjust to see the result too. You can locate the file
following on your system and open it with VLC player to confirm it’s recording
index.js properly.
package.json
recordings STEP 11: TEST THE SYSTEM
views
Now we can check that Node.js can handle this functionality too.
Create a symlink with the command: Firstly, edit index.js and update the variable videoInput with your
RTSP stream address. Next, we’ll start the server.
To install all the dependency libraries that are listed in the package. nodejs index // tell node to start the
sudo npm install If you open the two links below in your web browser, you should
see it record. The optional parameter after record allows you to set
duration with the request.
STEP 9: SET UP YOUR IP CAMERA
http://localhost:3000/record
Follow the instructions that come with your camera to ensure RTSP http://localhost:3000/record/60
streaming is enabled and running. Ideally, the camera will have a
fixed IP address so it won’t change. For our purposes, we’ve used We have set up a simple file-listing system, and an in-browser player
the Jaycar TECHview 1080p IP camera, since we had one already (using HTML5). Simply navigate to http://localhost:3000 to view a
here. Some of these cameras require Windows and plugins to list of the recordings. You can click on any recording to view it in-
access/control the camera. Once you have the camera working: browser [3].
Consult your camera’s documentation for the specific query There’s a good chance that you don’t want to log on and open
required, as everything after the IP address can send commands terminal, so we’ll set the system up to run by itself. To do this, we
to the camera regarding the type of stream, resolution, and various will use forever js - https://github.com/foreverjs/forever ››
other options.
This is where the fun really begins. There are many instances where
you would want to trigger recording via hardware; perhaps a motion
sensor, an entry sensor, or a “panic button”. Even for something
you may have set up, such as an automatic pet feeder to check “did
the cat come and get its food this morning?”. More importantly, you
can interface it with something such as our Alarmduino project, to
record for a duration when the alarm is triggered, or even just when
someone has armed/disarmed the system, so you have a video Our code is already configured for the GPIO triggering. When you
record of events. push the button, recording will start. But it’s important to note, you
can use this code to trigger from any 5V logic signal.
var pin = 7;
You can change this to whatever number you prefer. We are keeping
things simple with only one GPIO interfacing pin, but you could
easily expand this to multiple pins (and even record different
cameras based on the pin that's triggered).
From line 121 you’ll find our GPIO callback function. You can
modify this in all sorts of ways, but here we’re basically just telling
the system to listen to the GPIO pin, and whenever anything
changes, perform some functions. In this case, we trigger
“startVideoCapture()” function. It would be possible to expand on
this to send an email, turn on a light, or all sorts of other functions.
When reading the stream at full HD resolutions, it would quickly
overload the processor. It seemed to work fine at a lower resolution
gpio.on(‘change’, function(channel, value) { (such as 720p, perhaps smaller), without interfering with the
if ( value === true ) { DVR functionality. The playback capabilities will depend on the
console.log(‘Triggered’); resolution, video format, and network speeds.
startVideoCapture();
} HARD DISK SPACE: Inevitably, you’ll run out of hard disk space. While
}); it’s possible to record to any connected storage device with a minor
configuration change, it will probably EVENTUALLY run out of space.
gpio.setup(pin, gpio.DIR_IN, gpio.EDGE_BOTH); It wouldn’t take too much to create a scheduled process in Ubuntu,
which cleared out the oldest files to maintain free disk space.
Getting
Some Air
You may recognise CREATE UNSW from last month’s
VIVID Installation feature. Well, they’re back - this
time with some amazing UAV designs!
◄ LEFT
Substantial planning goes into every
build and modification along the way.
CREATE UNSW has created several UAVs, and you’re now working and autonomously determine an appropriate flight path to image a
on your third big design. Tell us a bit about what the goals are, and field, after having received a file that has field bounds. It also had
what’s driving the outcomes. to be capable of autonomously operating (i.e. take off, collect data,
land, transmit data), as well as function unattended for multiple
Individuals and companies are starting to see the potential of days, take multiple flights per day, use wireless connectivity to
UAVs in civilian applications. Each of our UAVs are designed transmit and receive data, operate in winds of up to 32km/h, and
for competitions; they challenge this emerging technology and use data connection to determine if weather conditions are safe for
demonstrate the utility of UAVs for civilian applications, particularly flight.
in applications that will save people’s lives in the future, and that
will improve workflow in the agricultural industry. IBIS is being designed for the 2018 Outback Challenge: Medical
Express. The competition is much the same as the 2016
The MUGIN was designed for the 2016 UAV Outback Challenge: competition, but now teams must detect an A2-sized landing marker
Medical Express, where they require teams to fly their UAV through and have the option to take on further autonomous related tasks,
a narrow corridor to a nominated GPS location more than 30km such as dynamic geofences.
away. The UAV then has to search for a fellow called “Outback Joe”,
survey a landing site, detect obstacles, and land autonomously That’s quite a challenge - sounds like you had (and still have) your
once he is found. “Outback Joe” will then place a “blood sample” work cut out for you! It’s hard to gauge size from the images on
on board and arm an activation switch. The UAV will then take off paper, but when you see someone working on it, it looks massive.
autonomously, and navigate back to home base. What’s the wingspan of these UAVs? ››
This controller comes with instructions! Some innovative construction methods are used.
›› The MUGIN had a wingspan of 2.6m, CROW has a wingspan of 2m flight. QuadPlanes have their pros and cons but for situations where
and IBIS is going to have a wingspan somewhere between 2m and you need high cruising speeds, endurance, and vertical takeoff and
2.8m (it’s still under discussion). landing (VTOL) QuadPlanes are the best suited.
Wow, that’s huge! What materials have been used in construction? Tailsitters and tiltrotors can be more efficient but there is
mechanical complexity in the design. In order to maximise the
With our small budget we tend to use materials that are cheap. efficiency the props need to be variable pitched because in vertical
Most of the team have a RC hobbyist background so we wanted to mode, props that have a flat pitch perform more efficiently in static
develop UAVs that used materials that were widely available off the air (vertically). However, in dynamic air (moving horizontally) props
shelf. The MUGIN was a store-bought airframe with a plywood wing with a sharper pitch perform better and provide more thrust.
structure, carbon fibre rods to reinforce the fuselage, fibreglass
fuselage, and a skin on the wing made from balsa and film. The QuadPlanes can take this to their advantage; because it can
wing was modified to attach the carbon fibre booms for the vertical vertically take off, you can design your forward flight prop and motor
lift motors using machined mounts from ABS. to be efficient at cruising speeds, since you do not need to take into
consideration the thrust requirements for taking off.
With CROW we wanted to experiment with making our own fuselage
and structural components. Due to time constraints, the wing was That’s awesome! It’s definitely a great hybrid. Blending easier
store-bought. It’s a foam core, Kevlar-skinned glider wing - yes, landing with high forward speed is definitely a great idea. Was
it’s very fancy but it’s lightweight and extremely strong, plus we there an existing design leveraged for this style of UAV, or did you
got it at an awesome price! The tail control surfaces are hand-laid start from scratch?
fibreglass on balsa wood. The interior structure of the fuselage is
plywood, the fuselage shell is from hand-laid fibreglass, the vertical When we first started working on a QuadPlane design back in 2015,
motor booms are carbon fibre, the motor mounts are machined from there was only a few teams and hobbyists working on the designs
ABS (potentially aluminium, very soon) and the various fairings and and code for Ardupilot (a shout out goes to Andrew Tridgell and the
joining mounts are 3D printed from ABS (they may be machined in team from Canberra UAV, and the Arduplane development team for
the future). working on developing the QuadPlane firmware).
In contrast, for IBIS we are aiming to experiment with laying One of the ones that caught our eye was someone named “wcolby”
other composites such as carbon fibre. None of us have had on YouTube who converted a Hobby King Bixlar 3 into a QuadPlane.
the opportunity to lay carbon fibre and use the vacuum bagging This prompted us to convert our Bixlar 3 (that we used for training)
process, so it’s going to be an awesome experience. We are aiming to a QuadPlane. There were no plans available so it was pretty much
to make everything ourselves, including the wing. “let’s strap some aluminium tubing from an old quadcopter, stick
some motors on and let’s see what happens”. At this point in time
Anytime you can learn new fabrication techniques it’s a great idea, the Arduplane firmware for QuadPlanes was still in beta so we had
so you then have that knowledge for future projects! The wings some interesting near misses. After learning the design quirks with
are styled like a drone for vertical takeoff/landing but with forward the Bix QuadPlane, we transferred what we learned into the MUGIN.
propulsion once it’s airborne, is that right?
CROW took some design features from Textron and Carbonix, such
Yes! The style of aircraft we make is called a QuadPlane - quad as the method of mounting the motors and the V-tail.
motors for vertical lift and a plane to give it long-range horizontal
Nothing like bolting two ideas together to see what happens! CROW is an autonomous agricultural surveying system. CROW
What’s powering these UAVs? can take off, survey a field, land onto a base station, recharge and
transfer data to the base station completely autonomously. CROW
The MUGIN was a hybrid system of a two-stroke DLE30 petrol will also check weather data and avoid flying if the weather is bad. It
engine with a 19-inch prop, and an X8 configuration of eight T-motor also has “scuttle buggy” landing gear, which allows the UAV to move
U7 KV420 electric motors running 18-inch props. It used two 6s on the base station to align itself to charge.
5000mAh LiPo batteries - one for each side. It drew a whopping 600
amps and had about a 3 minute flight time in vertical mode. It really is autonomous! With all that thinking going on, what sort of
control system are you using?
CROW was an all electric system. We had to optimise the power
system and propulsion system to get more endurance out of the two On all our UAVs, we are big fans of the Pixhawk flight controller.
6S 5000mAh LiPo batteries. It uses four T-motor Antigravity 4006 Pixhawk is an open-hardware project aiming at providing high-
KV380 running 14-inch props and one T-motor MN3110 700KV with end autopilot hardware to the academic, hobby and industrial
an 8-inch prop. We can get around one hour in forward flight and communities, at low cost and high availability. When we first
five minutes in vertical flight. started we were using the Pixhawk 1 and now we have moved up
to the newly released Pixhawk 2. It uses the open-source Ardupilot
For IBIS, we are going back to a hybrid system just for endurance software. For all the capabilities it has it’s the cheapest, most robust
and the energy density of fuel. flight controller; in my opinion, it’s as good as flight controllers
priced at $5000+.
Wow - 600A for vertical flight! Fuel definitely makes sense there,
and we can understand retaining hybrid technology to keep it all Ardupilot is the software we use on the flight controller. It’s a
going! Tell us a bit about the special autonomous functions of your professional-grade open-source, unmanned vehicle Autopilot
UAVs. Software Suite, capable of controlling autonomous multirotors,
helicopters, fixed-wing and VTOL model aircraft, ground rovers,
The MUGIN was designed for the 2016 Outback Challenge: Medical model boats, model submarines and antenna trackers.
Express, so it was designed to be a long range medical delivery UAV.
IBIS will have the same function as it is being designed for the 2018 Paired up with the flight controller is a companion computer.
Outback Challenge: Medical Express. These UAVs fly completely A companion computer allows us to improve the autonomous
autonomously to a known GPS point, search for a target, find a capabilities of our aircraft. We run a stripped down version of
suitable and clear landing spot, land, shutdown, collect a blood Ubuntu MATE with ROS, which is a pseudo operating system
sample, start up and fly back home. They are designed for 60km designed for robotics. One major reason for using ROS is that it
round trips. allows us to create nodes for each process, so if one process ››
›› fails it will restart it without causing the aircraft to fall out of the
sky. ROS has a lot of useful libraries for SLAM, image recognition and
path planning.
“Not falling from the sky” is pretty high up there on the desired
feature list, that’s for sure! What did you learn from the first few
One of the lear
developments that could be used on a subsequent builds? ning UAVs.
When we first started we had the good old hobbyist mentality, where
we strapped things together and hoped they would work on the Once manufacturing is completed, we then:
first try. That can work well but when you are in a competition with
top teams you need to have a bit more structure in the design and • Test the aircraft in manual and make any necessary changes.
manufacturing process, and allow plenty of time to test your design. • Tune the autopilot.
• Test autonomous features and make changes.
We have now adopted this build process: • Continue testing and making changes until we are happy with the
UAV.
• Break competition rules into functional specifications.
•Split functional specifications into mechanical, electrical and That’s a great procedure, and a solid process that can be applied
software categories. time and time again. When did the UAS team get started at CREATE
• Decide on sub teams under each engineering team. UNSW?
• Explore conceptual design.
• Undertake design and verification, which involves researching, In early 2014, members in CREATE ventured into UAV research, and
testing concepts, developing the CAD of our aircraft and testing began experimenting with flight controllers and multirotors. We then
software on our spare UAVs. decided to launch CREATE’s Unmanned Aerial Systems (UAS) team
• Review the preliminary design. in July 2014, as a student-led project group that was run under
• Apply further design and verification, taking in the changes from CREATE. From there, we developed connections with academics
the PDRs. who were researching the area, and we decided to enter a team
• Finalise the design with a Critical Design Review. to compete in the UAV Challenge: Medical Express competition in
• Begin manufacturing. September 2016. ››
Attention
UAS have several "learning UAVs" to help
with experimentation and familiarisation.
WANT MORE?
For more images, or to discuss this feature, visit:
https://diyode.io/003cbzw
To the Brink
and Back
It’s rare that you come across a great new Aussie-
developed piece of hardware, but Stephen Brinks at
3DBRINK is an exception to the rule, thanks to his
highly accurate Delta 3D printer.
RIGHT ►
One of the delta printers.
spberry Pi.
Powered by Ra
I love robotics and had been building small robots to show at A built in webcam? That’s awesome! Remote printer control
job interviews. A 3D printer is basically a robot, and when I first (with vision) is definitely a great feature for printing. I think all of
started seeing them they were simple machines so I knew I us have come back to a large print that’s been going overnight,
could make them better. only to find a blocked nozzle, or worse - a mess of filament
everywhere. What’s the coolest thing you’ve printed with one of
Bringing robots to job interviews? Why didn’t we ever think your printers?
of that? One major claim your printers make is that there’s
no bed-levelling required. There are some machines which A stormtrooper helmet! But on a more useful note I actually used
automatically level their print surface on startup, while others my first 3D printer to prototype and print parts for my new 3D
still require a manual calibration; but to have no levelling printer.
required at all? How did you achieve this?
That’s brilliant! When you started developing your printers,
I chose a more advanced system called a Delta. The bed does did you have a commercial intention, or was it an unintended
not move on a Delta 3D printer so when it is built the bed is outcome of the prototyping process?
bolted in. Typically this would cause another problem, where the
user can only print at one layer height, but I overcame this issue It was a result of realising I had a great design. While everyone
by having a box where the user can change the starting height was (and still is) making simple Cartesian 3D printers, the
of the print in the software, thus allowing for any layer height Delta geometry has huge advantages in speed and positioning
without adjusting the already-level bed. accuracy.
You’re certainly getting some great accuracy, which is usually From RAAF engineer to entrepreneur, that’s fantastic! Any
very difficult with large-sized printers. Was there a reason for advice to anyone else looking to create something and take it to
using belts over leadscrews? market?
Leadscrews were very expensive and slow at the time. The belts I started building 3D printers in my garage. You can build
work flawlessly in combination with the guide rails, and absorb and invent whatever you want to. Today we have advanced
backlash and vibrations which allowed me to use the Delta electronics and the internet, so add a 3D Printer and the sky is,
geometry for greater speeds. literally, the limit of what you can create.
Sounds like it’s been well-considered. We notice you’re using Sounds like great advice. It literally is at everyone’s fingertips! ■
Raspberry Pi and Touchscreen - it’s a great elegant control
platform. What led to that choice? GOT SOMETHING TO SAY?
To discuss this edition of Going Pro, visit:
I was developing my own software to run on a touchscreen but https://diyode.io/003pfwv
then the Raspberry Pi came out and they just kept getting better
and better. Now they allow my machine to operate over WiFi and
have a built in webcam.
How
over a TCP-IP network.
MQTT
CLIENT: A device on the network which connects to a broker. A
client can choose to subscribe, publish or both.
Works
PUBLISH: Messages are propagated around the network by
means of “publish” messages. Typically, a client will send a
publish message to the broker, after which the broker will
send publish messages out to subscribed clients to complete
transmission of the message.
- by Tim Blythman
A COMPLETE SPECIFICATION OF THE MQTT V3.1 PROTOCOL:
http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/
MQTT_V3.1_Protocol_Specific.pdf
The MQTT protocol (and its different versions) have a lot more The MQTT Light Switch project only uses Level 0, as higher levels
features than what is mentioned here. The following is based on require more overhead for the Arduino. In any case, if the message
my research in developing a simple MQTT client, which can work on is not acted upon immediately, the user can manually resend. Level
an Arduino for the MQTT Light Switch project and interact with the 2 might be used in something like an instant messaging app, where
mosquitto broker. you’d only want one copy of a message to be received.
Level 0: receipt not guaranteed (no acknowledgment) A “publish” message may not contain wildcard characters, while a
Level 1: receipt at least once guaranteed “subscribe” message can.
Level 2: receipt exactly once guaranteed
The “#” character can stand in for any number of levels, so that To prevent an idle connection being dropped, a client might send a
subscribing to house/# will receive messages relating to house/ PINGREQ packet:
livingroom/lights, house/kitchen/lights, house/alarm and even
house topics. Client: Sends PINGREQ packet
Server: Sends PINGRESP packet
The “+” character can stand in for a single level, so that subscribing
to house/+/lights will return messages relating to house/ The MQTT Light Switch project is set to do this about every minute to
livingroom/lights or house/kitchen/lights topics, but not house/ keep the connection alive.
livingroom/TV, house/alarm or house topics.
Before closing a connection, a client should send a DISCONNECT
Subscribing to “#” will subscribe to all messages coming through packet:
broker.
Client: Sends DISCONNECT packet
MESSAGE
If a client disconnects without sending a DISCONNECT packet,
The “message” is the content of the data that is sent to a topic. It is its “will topic” will be published to advise other clients that it has
effectively a string of UTF-8 characters, but the Arduino in the MQTT disconnected unexpectedly.
Light Switch Project is limited to interpreting these as ASCII. To send
a numeric value, it is recommended to send a string representation. The structure of the packets used in the MQTT Light Switch is
detailed here, starting with the CONNECT packet. If a server does
WILL not receive a CONNECT packet after a client connects to it, it should
disconnect that client.
A client can set up a “will topic” with the broker, which is a topic
that is published if the client disconnects unexpectedly (without
sending a disconnect message). Think of it in the sense of “last will BYTE VALUE MEANING
and testament”. This allows other clients to be informed if another 1 0x10 Connect Packet
client has gone offline unexpectedly. 2 0x0E 14 Bytes Left in Message
3 0x00 Protocol Name Length, MSB
The actual execution of the MQTT protocol occurs as a series of TCP- 4 0x06 Protocol Name Length, LSB (total 6 bytes)
IP packets. The first four bits of the packet identify its function, with 5 0x4D "M"
many packets only being two bytes long. 6 0x51 "Q"
7 0x49 "I"
A typical exchange (based on what happens in the MQTT Light 8 0x73 "s"
Switch) will be as follows: 9 0x64 "d"
10 0x70 "p"
Client: Connects to Server 11 0x03 Protocol Version (0x03 Means v3.1)
Client: Sends CONNECT packet to request a connection 12 0x02 Flags - Bit 1 Set Means Clean Session
Server: Sends CONNACK packet to signal that is accepts the client 13 0x00 Keep Alive MSB in Seconds
connection. 14 0x3C Keep Alive LSB in Seconds (Total 60 Seconds)
15 0x00 Variable Payload Length MSB
A subscribing client will do the following: 16 0x00 Variable Payload Length LSB (0 Bytes More)
›› In practice, the MQTT Light Switch sketch simply checks if the first
byte is 0x20, as the server will undoubtedly disconnect if it doesn’t 7 0x70 "p"
want to connect. 8 0x69 "i"
9 0x63 "c"
The example SUBSCRIBE packet below corresponds to a 10 0x6D "m"
subscription to “#” with QoS 0. The MQTT protocol allows multiple 11 0x65 "e"
topics to be subscribed to in the one packet, but for simplicity, 12 0x73 "s"
the Arduino code is only capable of one at a time. They can be 13 0x73 "s"
differentiated by using a different message ID. 14 0x61 "a"
15 0x67 "g"
16 0x65 "e"
BYTE VALUE MEANING
Part 2:
Alarmduino
Last month we set ourselves on the journey of exploring how alarms
work. The project, while fully functional, lacked some crucial features to
make it useful. This month we will expand on these sub-systems to better
understand exactly how to maximise their functionality. - by Oliver Higgins
Our alarm system is taking shape, but there are a few core enabling network connectivity, which allows us to enable
functionalities that make it a bit tricky to use in the real world. IoT functionality and control the alarm with a web app. We’ll also
Some of these are RFID key learning, and exit/entry delay. While add in an entry and exit delay to this system by defining particular
IoT capability isn’t really a critical functionality, it’s certainly nice to zones to have a no alarm period. And we’ll add a door strike
have, so we’ve added in the fundamentals of IoT arm/disarm, and a function, which will enable you to remotely unlock any door from
few other cool things too. your phone, before finally breaking out the unit with screw-headers
that will create a much more robust device.
THE BROAD OVERVIEW
To do all this, we have added three extra libraries: SPI, SD and
We need to extend the features that we implemented the first part Ethernet to our code. These are all required to enable the use of the
of this project. For this, we will implement some changes such as Ethernet shield and its hosted SD card slot. All three are included
adding a learning function to the RFID system to enable the user to with the standard installation of Arduino’s Processing. ››
add keys/fobs into the system; and adding the Ethernet shield and
+5V
ARM +5V
VCC 1 +5V
22
GND 2 GND 320R
V0 3
V0 4 A8
TEST +5V
R/W 5 23
320R
E6 A9
LCD
DB0 7 NC
GND NC NO COM
RST 49
BUZZER
ICSP 4
ETHERNET / SD
(DIRECT SHIELD PLUG-IN)
CIRCUIT DIAGRAM
After Part 1 was published, we had a few requests for a standard schematic to assist with
wiring. This is definitely worthwhile, so here it is! It's important to note that the Arduino
pins for the Passive and Active Zones are indicative only. Connect Active / Passive zones to
any of the configured pins. The key difference is to ensure grounding of passive zones. This
is also true for Relay Output and Buzzer. They demonstrate connectivity, however the circuit
supports multiples of these systems from different pins.
In part one we implemented a RFID reader that was used to arm and This sounds quite simple however, it ends up being rather complex.
disarm the system. This works quite well for that simple function, The Arduino system works by creating one main loop that continues
but it lacked certain elements that would make it more productive. until the unit is shut down. This idea works quite well for something
The primary limitation was that cards and fobs could only be added like an alarm system. We start the system and arm it, then simply
to the system manually. This wasn’t a terribly difficult process during run the loop through, checking all the zones to see if it is broken
prototyping, but once the unit is installed it’s more tricky. and start again. Where this becomes complex is when we need the
system to multi-task or thread code. ››
We address this by adding in the required functions to make the
system learn. One of the advantages in using the Ethernet shield is
that in addition to enabling IoT functionality it includes an onboard
A Long Press
SD card. We will use this function to store our RFID keys.
Goodnight
In the original version of the code, we created an array and placed
our keys as strings in it. We also defined the number of keys we
needed. We still have that limitation in that we need to specify the
number of keys, but we have set it up to have 16 keys in the system. Having a button for every function is not always practical. It is
This could very easily be contracted or expanded as required. common practice these days for buttons to be held down for
a “long press” and a “short press” thus enabling any button
We have added the SD card library and use it to read and write to serve two purposes. This reduces hardware complexity
the RFID keys to the SD card. When the array is initialised, all the but does present a software problem. In searching for an
elements are set to null. We then open the RFID.TXT file located in answer, we were able to correlate some quick solutions, but
the root directory of the card. many of them required multiple variables and quickly became
quite complicated. In this case, we needed to start the RFID
One limitation with the code learning however, is the lack of ability learning mode, but considering how often it would be used
to “unlearn” codes. The complexity here is that it’s not as simple we did not feel it warranted another button.
as a “scan and delete” operation. If you need to remove a tag from
the system, there’s a 99% chance you don’t have the tag handy to We already had code in the main loop that would check to
scan. And if you did, why not just take it from the person who has it, see if the test button was high and if it was then the test
similar to taking back a set of keys? If you cannot get the RFID key function would run; however, by using the millis() function
back, you would need to remove the RFID file on the SD card and we can time how long the button has been held down. In this
relearn all existing tags. case, we see if the button is still high after 500ms, and if it
is then we execute our other function, which in this case is
ENTRY AND EXIT DELAY rfidLearn. Where the limitation lies here is that we call a delay
for 500ms - half a second. In testing, this was enough time to
What our previous system lacked was the ability to define certain differentiate between the two; but feel free to experiment as
zones as delay zones. The theory behind this is that if your panel is this is quite a handy function to have. The code can easily be
located somewhere on the premise that may take you longer to get expanded to other buttons.
out, then the system will give you a defined grace period. Likewise,
upon re-entry to the premises, there is a delay through certain zones
before you deactivate the alarm. // Button 2 TEST
if (digitalRead(testButton) == HIGH) {
Also, we need to make sure all zones are OFF; for example, if you delay(500);
defined zone 3 to be a door that has a reed switch on it you would if (digitalRead(testButton) == HIGH) {
need to close the door, then arm the system. The system will give rfidLearn();
you grace to break that circuit and re-close the door before it will delay(2000);
seconds. You can change this time using the exitDelay variable. To testSystem();
the same way when you open the door or trigger a PIR that is near delay(200);
or on its way to the disarm panel; the system will give you a grace }
period in which to disable the alarm. If you do not turn it off, then
the alarm activates.
›› We could simply assign our entry and exit delay zones, then use INTERNET OF THINGS (IOT) ACCESS
a delay function to halt the system for a set period. However, this
stops the entire main loop from functioning which in turn renders all To bring the alarm into modern times, we need to implement some
of our zones as inoperable. We might as well just disarm the system. IoT functionality. Using the Ethernet shield, we have created a basic
How do we create a situation in which the main loop will continue, IoT runtime. To set it up you just need to put an IP address into the
even when certain zones are individually put in a time-limited idle code. Alternatively leave it empty to let the network assign one.
state?
When using the entry and exit delays we a different thread of code //IPAddress ip(10, 0, 0, 177);
while still letting the main loop continue. To achieve this, the system IPAddress ip();
difference between the timestamp and the current time is greater, disarmSystem();
the delay you have defined the system reverts to its normal state }
and triggers (on entry) or active idle (on exit). if (linebuf[15] == ‘U’) {
doorStrike();
}
A NOTE ABOUT THE MILLIS() FUNCTION: The millis function
returns the number of milliseconds since boot. Be mindful
that this returns an unsigned LONG and if you decided to use In this instance, we have created the following four functions: Arm/
it in conjunctions with integers (int) you would likely have disarm, RFID learn, and remote door strike control.
erratic arithmetic problems.
The arm/disarm function simply executes the armSystem() and
disarmSystem() functions when we send “A” or “D” via the web app.
The RFIDlearn function calls the rfidLearning function, which put the
system into a loop and waits for the user to scan a key.
What is We are going to use the same type of relay module to control the
a Door Strike? siren for the door strike. In this case, we’ll tie it to output04 (Pin33)
and create a new function called doorStrike(). This function will
serve to send the pin high, activating the relay which will then
A door strike is used to electronically control a door lock. switch on the door strike. Our next problem is how long do we
These are often used in banks and hospitals to stop members keep the strike active? The code itself is quite straight forward;
of the public going where they are not meant to go. They can we just add a delay() in after the pin has gone high. As this delay
be controlled from many different locations, require power to is something that you may need adjust later, we will add a global
be active, and move the mechanism out of the way, allowing variable called strikeDelay. From here we can easily modify.
the door to open. In our case, we are using an output pin to
drive a relay, which in turn switches power to the door strike. To control this via the IoT function, we copy the code located in the
In creating the function to control this, we can call it from any index.html file in the web app section. To create a new button we go
point in the program. This same functionality can be used to to this section of code and duplicate it.
realistically control any electric lock, automatic door, or other
electronically triggered access. You then title in “Unlock” and use the letter U as the keyCode. In
the INO file, we go to the Ethernet function and duplicate the “if”
statement for RFID. Change the R to a U and then we change the 12V SENSORS: One major request that has been made a few times,
function to doorStrike. is to expand the capabilities to use common PIRs. Generally these
run from 12V, so we’ll implement a circuit to allow some versatility
A MOVE FROM BREADBOARD of sensor use. This is especially important when you want to replace
an existing alarm system, and don’t want to have to replace every
One of the major hurdles we faced with installation previously, was PIR in the building.
the unit being on breadboard. We attempted to address this with
some basic Veroboard and create screw terminals to allow easy IOT SECURITY: It’s important to note that we still don’t have any
zone wiring and such. security around this functionality. Anyone who knows the system
could send a request to the system to disarm it. We will attempt to
Since most of our breakout is on the far-end header, we can use a overcome this with some basic “public/private key” implementation
34-way ribbon header to take the pins to Veroboard. The issue here in part 3 also. This involves creating a basic authentication method
is that this header on the mega is 36-way which is not a standard to help prevent unauthorised usage.
size. However, the top two pins are just 5V and GND. We can
therefore use a 34-way header and an angle or straight adapter to RFID MANAGEMENT: It makes sense to try and manage your RFID
easily plug into the current header. On the Veroboard, we’ll place a tags via a web interface. The Arduino isn’t really capable of serving
socket which then allows us to control the alarm’s I/O. This leaves a complex page, but expanding on our HTML package might yield
us only with 5V and GND to deliver to the Veroboard separately. We some useful abilities.
have added the three buttons and a breakout for the RFID; these are
all the items that are connected via the end GPIO pins. RFID TIME CONDITIONS: What if you had a cleaner coming each
week? Why not set access to allow them to disarm on a Tuesday, but
Trying to describe the wiring line-by-line is exhaustive, and not on other days? Or perhaps you have office staff? Management
describing the soldering of the Veroboard is virtually impossible. can disarm the system anytime, but general staff may only do so
Through this process, it has become clear this would be a better during daylight hours or on weekdays.
job for a custom PCB, which would solve all the problems we have
in getting everything reliably broken out with hard connections. CONTROL PANEL: We are creating a full 3D printed case for the
A custom PCB may really be the only way to handle this properly; controller. The case is easy enough to design, but how do we feed
however, if you took the time to construct your own Veroboard so many data lines to the controller? We may have to move to I2C for
edition, it would likely be just as robust (though fault-finding could the LCD to reduce the number of cable cores required. ■
be a challenge). We are continuing development of resolution that
adequately resolves this problem. NEXT MONTH: PART 3
We'll tackle some of the problems we have noted above, further
WHERE TO FROM HERE? improving our system for improved functionality.
In preparation for part 3 of this article series, we’ve found a few WANT MORE?
challenges, which we’ll attempt to overcome. Our end-goal is to To get the updated code or leave a comment, visit:
create a fully installable item, which can be practically installed with https://diyode.io/003pvzr
reliable operation.
Badge
FAR RIGHT ►
The schematic for
the badges.
BELOW ▼
Simon's PIC-powered
Halloween Badges
of Horror
SIMON LUDBORZS
Tinkerer, Maker and Dark Arts practitioner.
http://ludzinc.blogspot.com.au
@ludzinc
As with many seasonal projects we attempt, Simon ended up Home projects definitely provide a great basis for projects without
running a little late for Halloween 2015. But he got them finished, a commercial interest. Soft power buttons are so common in
which now makes him early for Halloween 2017! We were commercial products, but definitely not so much in hobbyist
impressed by how compact his creations were, as well as the projects. The finished units look so intriguing - are they simply
creative use of PCB material to make the entire unit, so we caught etched double-sided PCB material?
up with Simon to find out more.
Yes. I had experimented with shining LEDs through etched FR4 in
We were quickly impressed by your creativity here. What inspired the past.
you to make your own Halloween badges?
That’s a clever use of PCB material without making it overly
I had a bunch of 16F648s wasting away in a drawer, some complex. Did you make the boards yourself?
inspiration from the kids, and a need for a simple project to give
CircuitMaker a good run. Why did I have a bunch of 16F648s lying Prototypes, yes; but I have access to a PCB mill at work (LPKF
around? They were leftovers as my home projects have all migrated Protomat). It’s a nice machine but a lack of solder mask and SMD
towards Arduino/ESP8266. Also, I use my home projects to learn doesn’t mix well! Final boards were from Elecrow, and I loaded the
“things” I don’t get to do at work. So for this project, I wanted to parts myself. I also used a homemade solder stencil and frying-pan
experiment with low sleep currents in a battery operated device. reflow.
Even with 20+ years as an engineer, I had never implemented a soft
power button.
The kids love ‘em! I nailed the target audience there, first shot!
Adults, unfortunately, don’t really get it though.
Well, it was the kids’ idea in the first place! If you were designing
from scratch again, what would you change?
You mentioned you had to learn about low-current sleep. Can you
Reading & Resources:
explain what you learned, and any challenges you had?
► SIMON'S BLOG
http://ludzinc.blogspot.com.au/2017/06/
RTFM, which means “Read The F**king Manual”! I laid out the
i-didnt-say-which-christmas.html
design “just like I always do” (internal pull-up resistors, chasing
► PCB DESIGN AND SCHEMATIC
minimum parts count), but didn’t read up what would use the least
https://circuitmaker.com/Projects#/
amount of current. It turned out that external pull-downs were
digital%20pumpkin/7//1
better in this case! Another challenge was how to measure sub-
► PIC SOFTWARE
microamp currents. To do this I built my own current shunt amplifier.
https://github.com/ludzinc/LED-Trinkets
THE ADVENTURES OF CIRCUIT MODD
NEED IT!
SCANNING...
GOODBYE!
REALLY?
*CLICK* WAIT!