0% found this document useful (0 votes)
91 views101 pages

DIYode September 2017

This magazine issue includes articles on building an interactive robotic dog with Arduino, using voltage regulators, and building a Raspberry Pi video event recorder. It also contains information about a free 408-page electronics catalogue included with the issue from Altronics, and details a competition to win one of 10 robot kits for building the magazine's "Somewhat Autonomous Machine" robot project.

Uploaded by

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

DIYode September 2017

This magazine issue includes articles on building an interactive robotic dog with Arduino, using voltage regulators, and building a Raspberry Pi video event recorder. It also contains information about a free 408-page electronics catalogue included with the issue from Altronics, and details a competition to win one of 10 robot kits for building the magazine's "Somewhat Autonomous Machine" robot project.

Uploaded by

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

YOUR FAVOURITE ELECTRONICS IN A MAGAZINE!

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.

Call a Bradford Energy Concierge on 1800 332 332

Calculate your solar savings at bradfordsolar.com.au


The Next Phase of
DIYODE Magazine
It’s hard to believe we’re already several issues in. The good news is,
we’re loving every minute of it!

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.

Unfortunately for international subscribers, the cost of freight was


simply too prohibitive. If you’ve picked this issue up as a back issue
from some time in the future, then I hope the robots are friendly, but
sadly you won’t get the Altronics catalogue either!

As the issues continue to flow, we recently found ourselves tick over


5,000 Facebook fans. This represents a milestone for any social
media presence, and we're excited it happened so rapidly.

For all of our new subscribers and readers discovering DIYODE


EDITOR-IN-CHIEF DIYODE MAGAZINE IS Magazine for the very first time, welcome! We're excited to see our
Rob Bell AN INDEPENDENT PUBLICATION.
audience grow each and every day!
EDITOR Published by B.E. DIYODE Pty Ltd
Analee Gale
ACN 616 556 622
One extremely exciting piece of news we received recently was
TECHNICAL EDITOR ABN 50 616 556 622 from Jaycar Electronics. As of September they'll be stocking the
Bob Harper
Level 1-2, 156 Mann St,
Raspberry Pi 3! This is huge news, since their network of retail
STAFF WRITERS Gosford NSW 2250 Australia locations across Australia and New Zealand provide a convenient
Oliver Higgins
Daniel Koch © 2017 No part of this publication may be
way for many of you to "grab some pi". At the time of printing this,
Tim Blythman reproduced without written authorisation. All we don't know the extent of the range of Pi and accessories that are
contributed content is owned by the authors
PROOFREADER
coming, but it's great news. So make sure you tune in to Jaycar's
and reproduced with permission. All product
John Bourne names, logos, and brands are property of their email or social pages for full details.
respective owners.
CREATIVE LEAD
Jennifer Holland Printed by PMP. As we continue to find our feet producing DIYODE Magazine each
CREATIVE &
month, we constantly strive for more comprehensive projects, and
Newsagent distribution within Australia
DIGITAL TEAM managed exclusively by Gordon & Gotch. are always looking for ways to continually raise the bar.
Luke Parsonage
Kayla Gourlay ISSN: 2207-8045
Melanie Heard One of the challenges with microcontrollers and single board
Mike Lewis Print subscriptions are available to Australian
Danielle Bell
computers is taking them from a breadboard prototype, to a robust
residents for $9.95 per issue including GST.
Jacqui Creasy See diyodemag.com for international and reliable circuit when using extensive interfacing. Soon we will
subscription pricing.
CONTRIBUTORS
be taking on this challenge with our projects, whenever it's feasible
Greg Christenson All prices quoted in AUD including GST unless to do so. Whether the solution requires a printed circuit board, a 3D
CREATE UNSW noted otherwise. All prices are correct at time
Jason Greenlow
printable case, or perhaps just a little solder... our goal is to ensure
of printing and subject to change without
Fergus Haines notice. that you can prototype easily, but also safely transport the finished
Matt Lacey
project from the workbench in a reliable way. Whether the solution
Simon Ludborz ADVERTISE WITH US
[email protected] for a particular project takes a single issue or has multiple stages, it
will get done.
CONTACT US
[email protected]
+61 2 4326 0160
Please enjoy issue #3, and thank you for your continued support.
FOLLOW US
@diyodemag
Rob Bell

4 Issue 003 September 2017 diyodemag.com


WIN 1 OF 10
SAM ROBOT KITS
OK, so this Somewhat Autonomous Machine is not going to
make your coffee or go to work in your place, but this basic
robot will roam around trying not to bump in to things.

All you need to put it together, are a few tools and the
"This is SAM" project on page 58 of this issue!!

HOW DO YOU ENTER? KIT INCLUDES:


Simply head over to https://diyode.io/003comp 1 x Arduino UNO Compatible Board
and tell us in 50 words or less, what cool things 1 x L298 Motor Controller Board
you'd like to see a simple robot be able to do? 1 x Ultrasonic Sensor Board
1 x 4-Wheel Motor / Chassis Kit
Entries close 11:59pm 30th September 2017. 1 x 3D Printed Mounting Chassis
Winner to be announced via our email newsletter 1 x Battery Holder & Batteries
and social media channels. Terms and 1 x Jumper Kit
conditions apply.

It's all thanks to our friends over at


Jaycar Electronics: www.jaycar.com.au
72 46

50

91

20

6 Issue 003 September 2017 diyodemag.com


78 FEATURES:
■ G OING STEADY
Accurate Voltage Reference 14
■ ELECTRONIC HOMEBREW
Building Your Own Computer 30
■ MAN'S BEST ROBO-FRIEND
You Might Recognise Him... 46
■ COLD POWER
An ESKY Power Bank 64
■ GETTING SOME AIR
Impressive UAVs 78
■ BADGE OF HORROR
A Halloween Treat 96

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

diyodemag.com Issue 003 September 2017 7


NEW & REVIEWED

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

8 Issue 003 September 2017 diyodemag.com


Maker
Favourites
available from www.CoreElectronics.com.au
NEW & REVIEWED

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!

10 Issue 003 September 2017 diyodemag.com


NEW & REVIEWED

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 ››

Print Your Own:


► MARBLE MAZE
https://www.thingiverse.com/thing:1385312
► VASE
https://www.thingiverse.com/thing:481259
► GECKO
https://www.thingiverse.com/thing:1363148

diyodemag.com Issue 003 September 2017 11


NEW & REVIEWED

›› 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

Do we love the LulzBot series? Absolutely! In fact, they are now


- officially - our in-office printers. We really can’t fault them.
So far, our focus has been on solid, repeatable prints; we have

LulzBot Mini: LulzBot TAZ 6:


RRP (AUD INC. GST) $1795 $3495
MAX PRINT SIZE 152 x 152 x 158mm 280 x 280 x 250mm
PRINT VOLUME 3650cm2 19600cm2
MAX PRINT SPEED 275mm/sec 200mm/sec
LAYER THICKNESS 0.05 - 0.50mm 0.05 - 0.50mm
SELF LEVELLING YES YES
SELF CLEANING YES YES
PRINTING METHOD Tethered Tethered or Standalone (4GB SD included)
DUAL HEAD CAPABLE NO YES (Optional)

12 Issue 003 September 2017 diyodemag.com


FREE DIGITAL EDITION
WITH PRINT PURCHASE!
GET ADDITIONAL RESOURCES
Digital resources are available online, via the links we publish at the end
of each article. If you're a subscriber, you'll automatically gain access to
all articles via your online account. If you have purchased a print edition,
you can create a login and unlock these resources for free.

ACCESS YOUR CONTENT


Just go to diyode.io/003digi and use the access code below.

ACCESS CODE: 700256


FEATURE

Based on the math, an


output of 4,096 millivolts
works out to 4,096 distinct
steps with 12 binary digits.
Going
FEATURE

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.

diyodemag.com Issue 003 September 2017 15


FEATURE

Mounting to the front panel. Testing display contrast.

›› 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.

16 Issue 003 September 2017 diyodemag.com


FEATURE

That sounds thoroughly planned and executed. If you had to start


this project from scratch again, what would you change?

I am very satisfied with the evolution of the current design that I am


ABOVE ▲
The finished control board. working on now. But it would be interesting to build it using a four-
layer board, as it would help with the circuit routing, and enable me
BELOW ▼
to make improvements to the ground and power planes.
Greg's awesome array of self-made
bench hardware.
That would definitely help tidy things up sometimes, but what you
We did notice you had stacked it with some of your other devices have is already exceptionally clean too! What are you working on
- that’s great thinking. With a device that has such tiny tolerances, now?
do you have problems with EMI or anything else that could create
fluctuations or imperfections in the output? I am currently working on revision 2.24 of the Programmable
Voltage Reference, which includes upgrading the fixed voltage
I tried to design the board to reduce internally generated noise and references, and an updated negative bias supply. A dual-channel
EMI as much as possible. Some of the noise/EMI reduction design Programmable DC-Load based on the IXYS L2 series of Linear
choices include: MOSFETs, and a 10.000V precision reference using some 35-year-
old Analog Devices AD584 reference ICs.
• A Maxim Integrated MAX14931 digital isolator for the DAC SPI bus
to transfer the digital signals between the two different power That sounds fantastic - we’ll be watching out for your next finished
domains project! Thanks for taking us through your Programmable Voltage
• Lots of decoupling capacitors throughout the board Reference! ■
• Large ground plane on the bottom side of the board
• Separation of digital and analog sections of the board, and GOT SOMETHING TO SAY?
additional shielding for the analog section To discuss this feature, visit:
• Choice of an all metal aluminum enclosure https://diyode.io/003xvpd

diyodemag.com Issue 003 September 2017 17


YOUNG
MAKER FUN.
No soldering required! Kids use a conductive pen and magnetic modules to make a
circuit come to life in the included sketchbook, which has examples and templates
to work through. The modules magnetically attach using the steel sheet that goes
behind the paper. Visit our website for videos and full list of contents.

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.

TEACH YOUR KIDS ELECTRONICS


WITH LITTLEBITS
A clever range of kits to help educate and inspire kids (and yourself)
about electronics and programming. Each littleBits kit has easy-to-use
colour-coded building blocks, with step-by-step instructions.

CREATE TOUCH-ACTIVATED INVENTIONS ONLY


TO CONTROL YOUR STUFF KJ-9120
This Rule Your Room Kit
$ 9995
transforms any boring old
object into an awesome,
interactive invention.
CIRCUIT STICKERS
Prank mom, create STEM STARTER PACK KJ-9330
games from scratch and Uses copper tape with component stickers to allow kids to
defend your domain from merge art and electronics. Includes copper tape, batteries,
intruders. Ages 8+. LEDs and heaps of templates and exercises, including
circuits, switches. Even the box can be turned into a project!

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

jaycarelectronics @JaycarAU @jaycar_electronics Call Us 1800 022 888


FUN WITH
ROBOTICS.
$ 5995

$ 6995
Battery not included.

3-IN-1 ROBOT ARM KIT KJ-8916


ALL TERRAIN ROBOT KJ-8918 Capable of 5 separate movements and can easily perform
complex tasks. The kit is supplied as parts and makes
Use the 6 terrestrial tracks/crawlers to create a an excellent project for anyone interested in robotic
working gripper, rover or forklift. Electric motors construction. 100g lift capacity. Requires 4 x D batteries.
and detailed instructions included. Requires 4 x
ALSO AVAILABLE:
AA batteries.
USB INTERFACE KIT KJ-8917 $49.95

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.

MEET EDISON KR-9210 INTRODUCING


A compact, pre-assembled robot that
ONLY MBOT KR-9200 ONLY
is built to last. Pre-programmed with
6 robot activities set by barcodes,
$ 99 95 An easy-to-assemble, entry-
level robot that can avoid
$ 199
can be programmed using simple obstacles, follow lines, play
drag-and-drop programming soccer, and more. Control
blocks or a Python-like written from your Smartphone
language. Modular and easily or Tablet using the freely
expandable using LEGO® available app, or program
bricks. Ages 5+. using simple drag-and-drop
programming blocks or
Arduino® IDE. Ages 12+.

TORQUE MULTIPLICATION SPIN IT UP GEAR SHIFT BRING TO LIFE


Gearbox set with 3V 12,000 RPM motor. Hobby motors. 1.5-4.5V. 2mm shaft. 7 piece 48/12 gears & pinion set, and 3 Micro servo motor small enough to
Can be stepped down to six times from 3V 7.94GCM 20MM DIA. YM-2706 $3.50 piece spur gear set for hobby applications. connect directly to an Arduino Board. 3.5-
3,000RPM to 3 RPM. YG-2730 4.5V 17.86GCM 24MM DIA. YM-2707 $4.95 GEAR SET YG-2630 $9.95 6VDC. 1.6kg.cm @ 4.8V. Suitable pan and
SPUR SET YG-2632 $8.95 tilt bracket (XC-4618 $4.95). YM-2758
YG-2630

FROM FROM
$
12 95 3
$ 50
8
$ 95 9
$ 95

For our extensive


STEM range, visit:
www.jaycar.com.au/stem
Prices shown in $AUD. Savings off original RRP. Valid to 30 Sept, 2017.
PROJECT

TOUCH SCREEN
TIME-LAPSE
SLIDER

Want to take incredible time-lapse


video images? This time-lapse
slider will enable you to introduce
motion into videos, to add genuine
WOW factor; and all you need is a
basic camera. - by Oliver Higgins

We’ve all seen movies that include those amazing time-lapse


videos of fast-moving cloud patterns or the depths of the Milky THE BROAD OVERVIEW
Way. But have you ever wondered how you can create that dynamic,
smooth motion in your own videos, making them more reminiscent This project is broken down into three core areas. The unit is
of Hollywood blockbusters? The dolly is a fundamental piece of controlled by a Raspberry Pi 3, and for this project we are using the
film-making equipment; it allows a smooth transition to bring Raspberry Pi 7” Touchscreen LCD. We are using Tkinter and Python3
your audience into the action. However, with the advent of digital to create a Graphical User Interface (GUI), allowing the user to work
cameras, we now all have the ability - when coupled with a little in the field without the need for a mouse or keyboard (if you missed
bit of tech know-how - to create a sequence of images that can be it, we explored the Raspberry Pi (RPi) GUI in Issue #2). The RPi is
stitched together to create stunning 4K video renders. Both can then connected via the GPIO port to a breadboard or Veroboard, to
be achieved with this project. control everything from there.

The control unit uses a form of Pulse Width Modulation (PWM)


to get the slider unit to move. When used as a video slider, it just

20 Issue 003 September 2017 diyodemag.com


PROJECT

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 ››

diyodemag.com Issue 003 September 2017 21


PROJECT

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

22 Issue 003 September 2017 diyodemag.com


PROJECT

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. ››

PARTS REQUIRED: JAYCAR ALTRONICS


1 x Stepper Motor Controller YM2754 J0070
1 x Raspberry Pi 3 with NOOBS XC3630 Z6302B
1 x 7" Touchscreen Monitor - Z6309
1 x 330Ω Resistor RR0560 R7546
1 x Red LED ZD0150 Z0800
1 x 4n25/4n28 Opto-Isolator ZD1928 Z1645
1 x 3.5mm Stereo Socket PS0134 P0084
2 x Hall Effect Sensor Modules ZD1902 Z7275
2 x Rare Earth Magnets LM1622 T1466
1 x Emergency Stop Switch (Optional) SP0786 S0820

diyodemag.com Issue 003 September 2017 23


PROJECT

Adafruit T-Cobbler Plus


for Raspberry Pi
3V3 5V

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

MOSI GND DC+


MISO #25

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

24 Issue 003 September 2017 diyodemag.com


PROJECT

5V

Vin GND 12 1 (NC) 6


360R

OPTO
24
2 4N25 5
RASPBERRY PI

25
3 (NC) 4
18

23

16
OUT OUT SLEEVE
DIR-
DIR+
PV-
PV+
EN-
EN+

HALL EFFECT HALL EFFECT TIP


12V/3A STEPPER 3.5mm
DC+ CONTROLLER SOCKET
V+ GND V+ GND
DC-
A+
A-
B+
B-

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.

On the gantry itself, we have placed a magnet at each end. When


it travels towards the end, the magnetic field triggers the hall
effect sensor, which sends pin 24 or 25 high. When this occurs,
the stepper motor is shut down (or sent in the opposite direction).
Please note: depending on your magnet and hall effect sensor
mounting, you may need to flip one to make it work. The LED
indicator is dim when not active (ie; the gantry is far away), and
bright when active (ie; the gantry is near). You should test this with
your magnet visually before activating the stepper motors.

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 ››

diyodemag.com Issue 003 September 2017 25


PROJECT

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!

THE SETUP COMPILING THE IMAGES

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

26 Issue 003 September 2017 diyodemag.com


MADE
THE
THING?
Now Show it Off!
Each and every month we shine a spotlight on impressive
projects from the electronics and maker community. We’ve
already seen amazing projects like Thomas’s Pi Powered
Sprinkler and FRED the Tracked Robot from Royce in Issue
1, Arjen’s Autonomous Robot Caterpillar in issue 2, and
Greg’s Ultra-Accurate Voltage Reference in this issue, just
to mention a few.

Awesome ideas inspire others, so make all those late


nights developing your project count even more. Not only
will you get a buzz out of seeing your creation in print for
the world to see, you’ll know that you’ll probably encourage
other readers to get hands on to start or finish their own
project.

To show us what you’ve built, simply send us a few details


along with some image of your project, and we’ll get in
touch if we have a place for it in a future issue.

SUBMIT YOUR PROJECT:


diyode.io/003submit
MOONSHOTS

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.

What made you undertake the process of building your own


computer? Was it for understanding, intrigue or something else?

Intrigue would be an excellent word for it. I’ve been programming


since my early teens, and for a long time I regarded both assembly
MATT LACEY language programming and hardware as dark arts: magic best left
Co-founder of Proximity Insight. VIC, AU. to wizards! Then sometime around six or seven years ago I tripped
www.mattlacey.com over Nisan and Schocken’s book, “The Elements of Computing
@CodeSubversive Systems” (more information on this can now be found at
http://nand2tetris.org). This takes you on a journey from logic
gates through basic CPU design, all the way up to writing your own
Compared to a modern computer, you can't do a whole compiler and assembler. It took away a lot of the mystery, even if it
lot with with a 68K computer. But the knowledge that was focused on a virtual computer. That got me far more interested
comes with it, makes it all worthwhile. in what was going on below the software level.

It’s an interesting world, and can make you a better coder! How did
you get started?

30 Issue 003 September 2017 diyodemag.com


FEATURE

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?

I think I’ll call it a success when I have a custom PCB running


with basic serial IO, allowing it to be used as a computer from a
serial terminal on another machine. I’d love to get to the point of
it having it’s own video output and connector for a keyboard, but
I’m definitely regarding that as a future goal and not something I’m
looking to achieve anytime soon. My spare time is extremely limited
between work and young children, so I want to have a realistic goal
for the time being.

Ah yes... forget work/life balance, it’s the hobby/spare time balance


that’s difficult! For those that haven’t been down this path before,
can you briefly explain what the end outcome will be? Are you just
measuring pins, or do you have a more fancy approach to indicate
that you’ve succeeded? After attempting to create the circuitry for SRAM for the first time
(moving from a state where the CPU was correctly running a small
Right now I am measuring pins with a logic analyser in an attempt loop from EEPROM), everything went haywire. I pulled the SRAM
to add the SRAM to the system. The end outcome will be a machine from the breadboard to see if it was contention on the bus but no
you connect to from another computer, with a simple command joy. So I spent a few evenings trying to work out what was going on;
line interface that will allow you to load programs over the serial my logic analyser was showing anything but what I expected. After
connection, and then execute them and see the results. I’ve got a few frustrating nights I finally realised I’d transposed the address
a background in game development so some simple text-based lines for the EEPROM while “refactoring” my board layout a little.
games may well be on the cards. Somehow I even checked continuity on the address lines one night
and failed to notice they were hooked up backwards, because I
That sounds great! Tell us a little about the main processor you’re was too busy making sure there were no breaks in the circuit. I find
using. debugging code is often similar: you never check the simplest thing
that could be wrong because you automatically assume there’s no
It’s a Motorola MC68000P12, which is the 12MHz version of the way it could be wrong.
venerable 68000 with a 16-bit data bus. I’ve got a soft spot for the
68000 purely because it powered two of my favourite machines: Yes - sometimes the best thing is a walkaway and return
the Atari ST and the Sega Mega Drive (it also powered the Amiga manoeuvre, that’s for sure. What have you learned so far about
500 and Apple Macintosh, as well as some other computers and computing hardware that you didn’t expect to?
arcade machines). A few years ago I finally got my hands on an Atari
Falcon, which uses the later 68030 processor, and I used that as a That everything has remarkable levels of tolerance. I hate to make
good excuse to learn 68k assembly. I thoroughly enjoyed that and those more familiar with hardware cringe, but for the most part I’ve
it’s hopefully given me the knowledge required to write my own ignored timing requirements, skimped on bypass capacitors (I only
programs for this computer if I don’t use C. learned about those during the EEPROM programming), and I’ve
generally gone with a “try it and see” attitude. So far, everything
Ah Atari... What was the biggest hair-pulling moment during has pretty much just worked. One thing that makes complete
development? There’s always at least one! sense, which I hadn’t anticipated, is that different components are
designed to work with each other. My EEPROM chips ››

diyodemag.com Issue 003 September 2017 31


FEATURE

All About The EEPROM


›› work in an almost identical manner to the SRAM chips, and only
simple glue logic is required to pull everything together. I was
originally planning to use a CPLD to handle most of the logic, such
as address decoding, but while it was super fun to play with, the During the build of your computer, you became sidetracked with an
cheap Chinese dev board I bought (an eBay special built around the EEPROM programmer project. Was this to directly benefit your 68k
Altera MAX II) has been relegated to providing my 5V power (it in project, or intended for something else entirely?
turn being powered by USB) and the clock signal.
It was for the 68k project. I’d been a little gung-ho in my Ali Express
It’s true, many of these chips are exceptionally robust. What are you shopping while looking for EEPROM chips to use, and completely
doing now with the computer? failed to check the compatibility of the cheap programmer I bought
with the chips I wanted to use. The list on the page was huge so I
Cursing at it for the most part! I kid, that was just yesterday! Today made the assumption (yeah, I know) that it’d all be fine; naturally it
I’ve gotten back to being able to run code from ROM but with wasn’t.
address decoding and the like happening. With some luck by the
end of this week the RAM circuits will be working and tested as well. What are you using as the basis for your EEPROM programmer?

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!

32 Issue 003 September 2017 diyodemag.com


FEATURE

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 .

diyodemag.com Issue 003 September 2017 33


Make
September 2017

Your Mark Build It Yourself Electronics Centre®

NEW!
$ 29 .95
NEW!
K 9640
30
$

Tinker Parts Pack


Z 6440
NEW! A huge assortment of parts for experimenting and building.
Includes diodes, LEDs, switches, resistors, caps, strip board, a motor
& more. Normal RRP value $55!
BBC micro:bit GO Kit
The BBC micro:bit is a pocket sized codeable
computer with motion detection, compass, LED
display and Bluetooth on board. Designed to be fun
Inventa® MegaBox Kit
80
K 9670

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!

Official Raspberry Pi Reseller. Shop in store or online!


www.altronics.com.au | 1300 797 007 Serving makers since 1976.
25% OFF! Cut, Polish,
Grind, Sand
& Carve! NEW!
Micron® 172pc
Digital Rotary Tool Kit
Vernier This workbench essential is just the
Calipers shot for electronics projects, crafts,
Precision measuring hobbies and odd jobs around the
with ease! 150mm house! Powerful 130W motor (this
length, suitable for meas- is a real power tool!) with variable

$ 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

Q 0200B 25MHz $ 499 $ 39 $ 25


Digital Storage Oscilloscope - Beef up your test bench! SAVE 29% SAVE 30%
Perfect for those in R&D, product development or servicing. 2 channels with real-time 1GSa/s sampling.
Colour 7” TFT screen simultaneously displays waveform plus the measured wave voltage, peak to peak
plus RMS, frequency, duty cycle etc. Realtime adjustments can be made using included PC software. Infra-Red Thermometer Autoranging Multimeter
Stored data can be saved to a USB stick. 2 year warranty. Affordable and high spec IR thermometer
for measuring temperatures without contact. The perfect enthusiast multimeter! Features tem-
-50°C to 500°C. 12:1 resolution. Great for perature range (probe included) and data hold
technicians, mechanics, even food safety. function. 10A current range.

Micron® Top seller!


Handheld
Soldering
Iron Sale! T 2164

An iron for every occasion! $32.50


T 2401 & T 2405 are ideal for
general purpose soldering. $26
T 2487 features adjustable
temperature for more sensitive Smartphone/Tablet Repair Tool Kit USB Clip On 5x
Everything you need to disassemble and repair most
UP TO 20%
work. T 2483 is a heavy
duty 7mm chisel for tinning, smartphones and tablets - driver bits, plastic & metal Magnifier Lamp
workbench essential. SAVE leadlighting and auto repairs. spudgers, suction cup and more! See web for full contents The latest Inspect-A-Gadget magnifier
A list. is powered by a USB port and provides
a crisp, clear view of your workbench.
430mm long. 1.5m USB lead.

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.

No hassle 14 day money back guarantee on all purchases!


www.altronics.com.au | 1300 797 007 Serving makers since 1976.
Kits To Build... 30 in 1 Electronics Lab
Just like the old Fun Way lab kits!
Contains everything you need to
build a range of projects to
K 2545 encourage learning about
The Tremor $105 $92 electronic principles.
Effect Pedal Kit MintySynth® 2.0 $53.95
Build your own analog
$ 89 Synth & Sequencer Kit $ 75 Requires 2 x AA
batteries. $ 40 K 2204
Age
8+
effects pedal and tweak it A great intro to electronic music!
you suit your needs! Controls Plus learn about electronics and programming
level, depth, velocity, hard/ along the way.
smooth & true bypass. Tough
diecast case
K 8126
K 8122

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

Stock up on quality blank PCB Robo-Bug Builders Base


Includes wheels and legs. Two motor design. W 0884A
Copper clad fibreglass board. Make your own
Great for making your own Arduino bot.
boards & save! Single sided. $19.95
Stackable Header Sockets
Size (mm) Model Normally NOW 2.54mm spacing. 8.5mm plastic surround. $ 16
150 x 75 H 0753 $7.25 $5 11mm gold plated legs. $26.50
150 x 150 H 0754 $10.95 $8 Type Model Normally 3 FOR 10 for 171 Piece Heatshrink Pack
300 x 300 H 0755 $24.70 $20 1 x 40 pin P 5384 $4.45 $9 P 2135A $ 22 75mm & 45mm lengths in a range of colours & diameters
(3.2 to 12.7mm). 2:1 shrink ratio.
2 x 40 pin P 5386 $7.30 $15 12 Way Terminal Strips
NEW!
2 x 20 pin P 5387 $3.50 $8 With wire protect tabs for a safe and secure $32.50

$ 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

diyodemag.com Issue 003 September 2017 37


FUNDAMENTALS

1 3
Input at least OUTPUT
+14.5V +12V
7812

0V

outdoor cordless power tools running on 40V or even 58V lithium


batteries, this is a situation some of you may encounter when
Let’s look a little more closely at the LM7812 [1]. The “12” at the choosing power sources for innovative applications. The challenge
end tells us that this device will give a regulated 12V output. The is this: the higher the difference between input and output voltage,
manufacturer’s data sheet tells us that it can output in excess of the more heat is produced. There are graphs in most data sheets
1A with appropriate heatsinking, and that if we get this wrong, then showing the power dissipation (the amount of heat that will be
the device is equipped with thermal protection that shuts it down in generated measured in watts) for different input voltages. These
case of thermal overload. Useful stuff to know! are useful viewing if you are planning to use a regulator with a large
input voltage difference. Heatsinks [2] are bulky when they are
This is where the technicalities start. Inside this TO220-packaged capable of working hard, and they require good airflow, which isn’t
three-pin device, a reference voltage is compared to the output always possible.
voltage, and the error between the two is used to adjust the gain of
a series pass transistor, as a variable resistance, to cause a voltage So, where possible, the key really is to choose an input voltage
drop, until the output is equal to the reference value. that is 3V to 7V above the desired output voltage. Also, don’t think
that you could just cascade voltage regulators one after another,
This means you need at least 2.5V more on the input side than you stepping down; because the heat still builds up, and that is a very
want from the output side, otherwise the device will lose regulation inefficient way of doing things!
and the output will fall below the desired value. So you cannot use,
say, an LM7812 to give you regulated 12V from a 13.8V sealed lead Happily, these devices are available in 5V, making them quite useful
acid battery. for makers. In fact, there is even a special low-power version of the
5V product - the LM78L05 [3] - which is made in a TO92 package
Further hints are found in the data sheets. The devices can cope with a 100mA output. The TO92 fits on small project boards very
with a maximum input voltage of 35V (providing we don't exceed well, if all you need to power is a little logic and some sensors.
the overall power rating of the device / heatsink combination being
used). That’s quite high for most makers, although with some Actually using a voltage regulator doesn’t take too much effort. The
first step is to check the data sheets for the pin-outs. While on the
subject of data sheets, many people just search the internet for
2
pin-out information, but this has two pitfalls. The first is that the
image you find and glance at may not be the device you’re after, as
it may have been mislabelled or tagged incorrectly. The other is that
anyone can put anything on the internet, so the information you find
may be outright wrong. Using manufacturer’s data sheets will avoid
both of these problems.

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. ››

38 Issue 003 September 2017 diyodemag.com


FUNDAMENTALS

›› 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

4 +7.5V IN OUT +5V


7805
0V
10µF + GND 100nF

R2 ~= R1(Vo/Vi) = Vo x R1/1.25. IAdj is negligible when the


0V resistances are chosen low. Once the value of R2 is known, all that
is left is to decide if you will use a fixed resistor and go with the
nearest available value, or a variable resistor. An example, such as a
Voltage regulators really are simple to use when the desired voltage 25-turn screw-adjust trimpot, would give very accurate control over
matches one of the series of devices available. However, what do the output voltage; very useful for a number like 3.3V.
you do if you need a voltage other than those available? e.g. 3.3V?
As in circuit [4], circuit [6] has two capacitors to dissipate any
The answer comes in the form of another three-pin device, which spikes that may come from the supply, or the circuit, which may
definitely does require extra components in order to work. The interfere with the regulator. Good practice is to distribute further
LM317T is another TO220-packaged voltage regulator [5]; however, capacitance around the circuit if the circuit is particularly noisy.
this one has an output adjustable between 1.2V and 37V. The same
rule applies to the fixed regulators regarding input/output difference Next time, we will look further into boosting the output current, and
– the input must be at least 2.5V above the output voltage for some of the specialised regulators that are available. ■
regulation to occur. In the case of the LM317T, a fixed resistor of
240Ω is placed between the “output” and “adjustment” pins. These GOT SOMETHING TO SAY?
are both connected to ground by a second resistor. The value of this To discuss this edition of Fundamentals, visit:
resistor is what sets the output voltage. https://diyode.io/003stbm

Reading & Resources:


► LINEAR TECHNOLOGY – APPLICATION NOTE AN32
www.linear.com/docs/4126
► LINEAR TECHNOLOGY – APPLICATION NOTE AN140
www.linear.com/docs/43921
► TEXAS INSTRUMENTS –
LINEAR REGULATOR DESIGN GUIDE FOR LDOS: SLVA118A
www.ti.com/lit/an/slva118a/slva118a.pdf
► TEXAS INSTRUMENTS –
LINEAR VOLTAGE REGULATORS LM340/LM78XX
www.ti.com/lit/ds/symlink/lm340.pdf
► TEXAS INSTRUMENTS – LINEAR VOLTAGE REGULATORS
The formula for the LM317 is: Vout = 1.25V x (R2/R1) + IAdj (R2) www.ti.com/lit/ds/symlink/lm137.pdf
► 1980 VOLTAGE REGULATOR HANDBOOK
To find a given output voltage, decide on the value of R1, the fixed BY NATIONAL SEMICONDUCTORS
resistor. This was 240Ω in the data sheet, but is 120Ω in some other www.smcelectronics.com/DOWNLOADS/1980-VOLTREG.PDF
applications. Then find the current through the adjustment terminal,
which is 50µA - not a lot! This is the IAdj value for R1 values; 1k0,

diyodemag.com Issue 003 September 2017 39


PROJECT

The servo motors actuate


the light switch with no
electrical contact.

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.

40 Issue 003 September 2017 diyodemag.com


PROJECT

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

tape to mount them. With some experimentation in trying to tweak


mosquitto_sub -h 192.168.0.223 -t “#’ the angles, I quickly found that the 0° and 180° positions were
adequate; it was just a case of working out which one corresponds
to “actuate” and which one corresponds to “idle”. The below code
›› This will display all messages coming into the broker - we’ve cycles between the two positions.
subscribed to the “#” wildcard (all topics) on the broker. Open
another console, and issue these commands, again replacing the IP
address with your broker’s IP address: #include <Servo.h>
Servo s;

mosquitto_pub -h 192.168.0.223 -t void setup() {


lightswitch -m off s.attach(2);
mosquitto_pub -h 192.168.0.223 -t }
lightswitch -m on
void loop() {
s.write(0);

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);

probably working fine. }

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

#define MQTTBROKER “BROKER”


SCL SDA G 5V A
ESP13 0 1 2 3
3V3 G RXO TXO

#define MQTTPORT “1883”


3V3 G EN AD D
5V
KEY G

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.

42 Issue 003 September 2017 diyodemag.com


PROJECT

3 4

MQTT DASHBOARD APP


5
If using the MQTT Dashboard app, open the app and click the +
symbol to create a new client. The only data you will need are Client
ID (which is arbitrary, but it does appear as the name in the menu),
broker (server) address, and broker port (1883 by default).

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?

The beauty of MQTT is that it allows small devices to communicate


easily by having the broker do all the hard work in managing the
connections and where the messages need to go. ››

diyodemag.com Issue 003 September 2017 43


PROJECT

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:

At the heart of any system using MQTT is a broker, which


if(strmatch(topic,”lightswitch”) mediates all communication. In this project it is nothing more
&&strmatch(message,”on”)){ than a program running on a device on the network. For the
DEBUG.println(“Lights on”); sake of security, it is best that the broker is accessible only from
doservo(3,0,180,500); inside the network; but for testing purposes, there are also MQTT
} brokers on the internet that can be used, such as test.mosquitto.
if(strmatch(topic,”lightswitch”) org. If you don’t have your own broker set up, you can use this
&&strmatch (message,”off”)){ broker, but be aware that there might be a lot of traffic on it,
DEBUG.println(“Lights off”); which could interfere with your project’s operation.
doservo(2,180,0,500);
} There are versions for many operating systems at
https://mosquitto.org/download/, including Windows, Mac and
many flavours of Linux. As long as the device it is installed on
The if() statements simply match the topic and message to fixed is available on the network all the time, then it doesn’t matter
strings, so it is straightforward to replace these with your own, or where it is installed.
create extra ones. To read a numeric value, use the atoi() function,
which converts a character array to an integer: For Debian Linux, which will include a Raspberry Pi running
Raspbian, the following commands should be run on a
terminal window:
if(strmatch(topic,”temperature”)
&&(atoi message)>25)){
Serial.println(“Temperature is high”); sudo apt-get update
} sudo apt-get install mosquitto mosquitto-clients

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”);
}

You can even add publish functions to desktop devices, by making


shortcuts for the test commands we used earlier. ■

WANT MORE?
To grab the code or leave a comment, visit:
https://diyode.io/003dcvt

44 Issue 003 September 2017 diyodemag.com


PROJECT

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.

I found installing on Windows a bit more complicated, as it doesn’t


automatically handle library dependencies. The following was tested
on Windows 10, but should work on Windows 7 or later.

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

Then go into the web configuration interface, find services settings,


and make sure that the mosquitto service is enabled.

A good idea is to also ensure that your broker has a consistent IP


address, either through setting it to use a static IP address, or to
To check if the mosquitto service is running, press Win+R and type configure your router to always allocate the same IP address with
‘services.msc’. You should see the mosquitto service running. If it is DHCP - these setting vary between routers, but might be called
not present, try rerunning the mosquitto installer (it will recognise “DHCP Reservation” or “DHCP Allocation”. Check your router’s
that the .dll’s are in the right place and configure the service manual for how to do this.
correctly). If it is present but not running, select it and press “Start”
so that it looks like below: If you would like to understand more about MQTT as a fundamental
protocol, check out WHAT THE TECH on page 88 of this issue. We
have a full glossary of terms and functions using MQTT so you can
expand this technology further. ■

diyodemag.com Issue 003 September 2017 45


FEATURE

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?

I had previously built a full size K9 using plans from a robot


builders group. A change of vehicle caused me some transportation
issues and other factors prompted me to build a scale model.

46 Issue 003 September 2017 diyodemag.com


FEATURE

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.

K9 can be controlled remotely by using an Android app via a


Bluetooth module for its driving function. There is an onboard
4D systems module connected to an Arduino that has been
programmed to select K9 ear and tail movements, and to also
display animations.

Nice one! There’s so much more to it than just a screen and


Arduino though. How did you make K9’s body?

K9 is made from white acrylic sheet of varying thicknesses.


Each part is marked out and cut with a blade. Parts are bonded
together with a solvent, which results in a solid fused part.
Scaling was difficult due to the size of commercial switches
and display screen availability. Panel angles had to be modified That’s some real complexity to handle, without the use of CNC
to allow all the internals to fit and be accessed when required. or Laser - well done! All that gear must take some juice though -
The head internals were a trial and error, built to make the how is K9 powered?
mechanisms work in very limited space. Its final look was
achieved by paint shading and “weathering” so as to provide an As space and battery longevity was a premium, I selected a
extra degree of realism. 30C series LiFe 4200, 13.2V battery. Under full systems use the
battery can run for about two hours. Without drive motion it will
The paintwork is great, and does have a fantastic metallic look run for up to seven hours. In tank mode, an L298 dual motor
to it! Did you go through much trial and error with the first build? board runs the drive wheels. ››

Designing the shell by hand. Fitting the electronics to the smaller chassis was a challenge.

diyodemag.com Issue 003 September 2017 47


FEATURE

›› 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?

The biggest challenges were timing - the required completion date


for Oz Comic-Con was way ahead of our original build-time plans;
and the task of making this scaled down version look acceptable.

He's my 2nd best


friend. Aren't you K-9?
- DOCTOR WHO (TOM BAKER)
Build It Yourself Electronics
Catalogue OUT NOW!
An indispensable
resource for your
projects in the
year ahead!
• Over 1000 new products.
• 408 pages - our biggest
edition ever.
• Expanded data, tips and
articles.
• A great builders reference
for the workbench.
FREE for Australian DIYODE
subscribers this month. If
you didn’t receive your copy,
contact your newsagent, or
register to receive a copy by
post at:
altronics.com.au/catalogue

Download on Issuu Download on Scribd Download PDF


SECRET CODE

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.

To quickly recap, a variable is something we need to monitor and INDEX 0 1 2 3 4 5


change. We define the variable and allocate data to go into it. This is
then read by the computer and changed as the program progresses.
Say, for example, we want to create a program that calculates two Here we have declared a series of six integer variables, which gives
numbers. When we calculate two numbers, we allocate a container us six containers to use to store our information.
for the number, called A, and a container for our other number and
call it B. The user enters data into the calculator. The calculator then
gets the number from the A variable, performs the required math int x0 = 0

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

isn’t the best approach.

50 Issue 003 September 2017 diyodemag.com


SECRET CODE

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:

To access the element we simply specify the elements number


that we need. For example, to read back the information in the first unrelated[0] = "Ate breakfast"

element we use: unrelated[1] = "1789.25"


unrelated[2] = "My car is red"
unrelated[3] = 1950
x[0]

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.

x[3] var firstTask = “Ate breakfast”


float bankBalance = “1789.25”
var secretPhrase = "My car is red”

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.

diyodemag.com Issue 003 September 2017 51


SECRET CODE

My partner said, “Please go to


the store and buy a carton of
milk, and if they have eggs, get
six.” I came back with six cartons
of milk, they said, “why on Earth
did you buy six cartons of milk?”
“They had eggs.”
The joke here is the implication that "get six" applies to eggs.
As a human we pick up on this nuance. However a computer
sees this instruction as "buy 1 carton of milk. if the store has
eggs, buy six cartons of milk". There is no direct request to
purchase eggs made at all. This is one of the key considerations
to make when programming. Computers don't think like humans.

However when we access an element with the array, it is very


int studentGrade[15]; // This will give us an similar:
array of integers to store our student grades in.
studentGrade[0]=81
>>> shopping = [“potato”,  “tomato”, 9.99, 4.67]
studentGrade[1]=76
>>> print (shopping[1])
studentGrade[2]=84
tomato
studentGrade[3]=95
etc....

Before we finish arrays and move on to loops, we need to show


just how useful both can be when combined. The below code will
›› With the above array, we can access any number by just calling produce the same output for Arduino/C and in Python3. You can see
the index. We will digress here to discuss loops before bring them we have created our array in one line in the Arduino code, compared
both together at the end of the article. to our original declarations. Both sets of code declare the three
elements of the shoppingList array, which contains three items that
While we have done our best to be as “pseudo code” as possible, are strings.
the above code is very “C” syntax specific. This is because there are
some differences here when it comes to using languages, such as PSEUDO CODE:
Arduino/C and Python3. In Python, an array is referred to as a list.
As with other variables in Python, we do not need to specify the type
of the variable, but when using a list, not all elements must be of Put potatoes, tomatoes and beans onto my

the same type. You can mix in integers with strings and other data shopping list then

types. Go to the shop.


Get list out of pocket,

PYTHON CODE: Starting at the top, we read each item and go


looking for it.

shopping = [“potato”, “tomato”, 9.99, 4.67]


list1 = [“a”, “b”, “c”, “d”]
list2 = [1, 2, 3, 4, 5 ];

52 Issue 003 September 2017 diyodemag.com


SECRET CODE

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
}

PYTHON3 CODE: // Loop back to the beginning and increment x.


When x reaches 5, the loop will finish, and the
code will continue to execute.
shoppingList = [“potatoes”, “tomatoes”,  “beans”]
for item in shoppingList:        
    print (“Current item :”, item)
for (initialisation; condition; iteration) {
     statement 1;

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.

Condition is any logical condition that controls the number of times


DECLARE
the loop statements are executed. How many times do you want to
COUNTER
do this loop? Of course, it is capable of a lot more than this, but we
are using this example in the interest of keeping things simple.
INCREMENT
COUNTER
Iteration/increment is the increment/decrement of the counter.
When the loop finishes, does the counter count up or count down?

CODE Finally, this is some code you can run to test in


TRUE Arduino/C/Processing. This loop will increment 100 times and print
CONDITION each loop: ››

//Arduino code
FALSE
for(int x=0; x<100; x++){
Serial.println(x);
}

diyodemag.com Issue 003 September 2017 53


SECRET CODE

›› 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;

FADE AN LED    statement 2;


   iteration of variable;

This example comes from the Arduino guide on For loops, and is a } while (condition)

great example of a real-world application.

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

54 Issue 003 September 2017 diyodemag.com


SECRET CODE

A programmer goes out to get


some dry cleaning. His partner
told him, “While you’re out,
pick up some milk.”
He never came home.

In code terms, the instruction is "while you're


out, get some milk". It doesn't say "while you're
out, grab a carton of milk and come home".
While the "come home" instruction is implied
for a human, a computer would not pick up on
this assumption. Since it's then always "out", it
would continue to pick up more and more milk.

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

diyodemag.com Issue 003 September 2017 55


CONNECT,
OUR MOST
POPULAR
MODULES

INTERFACE, & SHIELDS


FOR YOUR NEXT

SHARE.
INCREDIBLE
PROJECT

SWITCH REAL DETECT REGULATE


WORLD DEVICES OBSTACLES THE VOLTAGE
1 CHANNEL 5VDC Ultrasonic distance Run your 5V Arduino
XC-4419 $5.45 module for distances projects from a
4 CHANNEL 12VDC up to 4.5m. 5V. Uses 6V, 9V or even 12V
XC-4440 $12.95 two digital pins. supply. 4.5-35V
8 CHANNEL 12VDC XC-4442 input. 3-34V output.
FROM
XC-4418 $19.95
5
$ 45 7
$ 95 2.5A max. XC-4514
7
$ 95

HEAT MOTOR TABS


DETECTION CONTROL ON THE
A pyroelectric Allows full control WEATHER
infrared PIR motion of two DC Measures both
sensor. Wide Motors or one temperature and
operating range stepper-motor. humidity. 0-50ºC.
and adjustable
delay. XC-4444
5
$ 95 3-30V motor voltage.
XC-4492
$1495 Humidity: 20-80%.
XC-4520
9
$ 95

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

PROTOTYPE POWER THE BREADBOARD WIRE IT UP! BUILD YOUR OWN


Breadboard with adhesive back for Adds a compact power supply to your A pack of 40 jumper leads of various Bare micro IC to prototype your project
mounting. 830 Tie points. 200 Distribution breadboard. Power from a USB socket or colours for prototyping. on a breadboard.
holes. 165mm long. PB-8815 DC. 3.3V or 5V switchable. XC-4606 PLUG TO PLUG WC-6024 ATTINY85 NEW ZZ-8721 $4.95
SOCKET TO SOCKET WC-6026 ATMEGA328P & XTAL ZZ-8727 $12.95
PLUG TO SOCKET WC-6028

FROM
$
14 95 9
$ 95
5 ea
$ 95
4
$ 95

NERD PERKS CLUB MEMBERS RECEIVE:

$25 JAYCOINS CARD REGISTER ONLINE TODAY:


WWW.JAYCAR.COM.AU/NERDPERKS
WITH EVERY $500 SPENT*

jaycarelectronics @JaycarAU @jaycar_electronics Call Us 1800 022 888


*Terms and conditions apply.
NANO TO MEGA:
ARDUINO-COMPATIBLE
BOARD COMPARISON GUIDE
There are a number of Arduino compatible main boards available at Jaycar,
and as you might expect, different boards will work better in different
situations. Here's a brief rundown and comparison chart on our boards so
you can choose the best one for your application.

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

UNO NANO LEONARDO LILYPAD USB MEGA


IC ATMEGA328P ATMEGA328P ATMEGA32U4 ATMEGA32U4 ATMEGA2560
PROGRAM MEMORY 32KB 32KB 32KB 32KB 256KB
RAM/EPROM 2KB/1KB 2KB/1KB 2.5KB/1KB 2.5KB/1KB 8KB/4KB
DIGITAL IO 14 14 20 5 54
ANALOG IO 6 6 6 4 16
PWM PINS 6 6 7 4 15
DIMENSIONS(MM) 75X53X13 46X18X18 73X53X13 51X50X7 108X53X15

Over 150 Arduino-Compatible


Boards, Modules & Shields available.
www.jaycar.com.au
Prices shown in $AUD. Savings off original RRP. Valid to 30 Sept, 2017.
PROJECT

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.

58 Issue 003 September 2017 diyodemag.com


PROJECT

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

The system needs to do something. This is the output, and it could


be as simple as turning on an LED (or activating a flame-thrower).
SET VAR
You may then evaluate this output (as an input) and determine if
the action has happened. The process will continue to run, monitor,
evaluate and loop.

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

diyodemag.com Issue 003 September 2017 59


PROJECT

›› 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

PARTS REQUIRED: JAYCAR ALTRONICS


Output Proportional 1 x Arduino UNO XC4410 Z6240
Echo to Range
1 x Ultrasonic Module XC4442 Z6322
1 x L298n Motor Control Module XC4492 Z6343
1 x Chassis & Motor Kit KR3162 K1092
1 x 8AA Battery Holder PH9209 S5034
8 x AA Batteries SB2333 S4955B

We have also created a 3D printable bracket to cradle the Arduino


and Motor Control module, as well as mount the ultrasonic sensors.
This isn't essential for operation, so don't worry if you don't have a
3D printer. However it does make setup easier.

No breadboard is required, but you'll need prototyping jumper wires


for most of the connections. Depending on your 4-wheel chassis kit,
you may also need to solder wires to your motors. They usually come
Object Ultrasonic
with everything you need already supplied, but in various states of
completion. A few minutes with a soldering iron will solve any issue.

60 Issue 003 September 2017 diyodemag.com


PROJECT

as different printers will handle vertical holes differently. We would


recommend using support structures, then clean, and file where
appropriate. Connect the trig pin from the US to pin 11, and echo to
pin 3. VCC to 5V and GND to GND on the UNO.

Using jumpers connect the following from the UNO to the L298N.
Connect the other GND to the ground on the L298N board.

The motor’s rotation will be dependent on the polarity of the power


applied. We colour-coded each channel when soldering the wires
on. If using two motors then connect each one to the motor to A
and B screw terminals. If you are using four motors, then connect
each pair as per the diagram [2], before connecting to the screw
terminals.

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.

More importantly however, it provides a secure mount for the


ultrasonic sensors. Since these provide our only sensory interface to
the real world in our basic code, it's important that they're mounted
correctly. If they're pointing up or down, you'll have problems with
getting ultrasonic reflections back and your robot won't know
when to stop (and will basically keep trying to go forward until the
batteries go flat).

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.

BUILDING THE CIRCUIT

There are no external discrete components required. If you are using


our printed chassis, we recommended fitting the US module first,

DUAL MOTOR DRIVER UNO


ENA 10
IN1 9
IN2 8
ENB 5
IN3 7
IN4 6
trig 11
echo 3
US GND UNO GND
L298N GND UNO GND

diyodemag.com Issue 003 September 2017 61


PROJECT

›› 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.

//Setup the Ultrasonic Sensor


int trigPin = 11;
int echoPin = 3;
//Setup Motordriver
//Motor A
int ENA = 10; // MCU PWM Pin 10 to ENA
int IN1 = 9;  // MCU Digital Pin 9 to IN1
int IN2 = 8;  // MCU Digital Pin 8 to IN2
//Motor B
int ENB = 5;  // MCU PWM Pin 5 to ENB
int IN3 = 7;  // MCU Digital pin 7 to IN3
int IN4 = 6;  // MCU Digital pin 6 to IN4
// defines variables
long duration;
int ob_distance = 20;//distance in cm
int motorSpeed = 75;//0-255

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
}

62 Issue 003 September 2017 diyodemag.com


PROJECT

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()

module. The pingSonar() function returns an integer, which is {

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();

(duration), which we then multiply by 0.034 (speed of sound) and delay(1000);

divide by 2, allowing for the round trip (since we're reading the echo backward();

of the original signal). delay(2000);


stop_all();
delay(1000);
int pingSonar() { turnLeft();
digitalWrite(trigPin, LOW); delay(1000);
delayMicroseconds(2); stop_all();
digitalWrite(trigPin, HIGH); }else
delayMicroseconds(10); forward();
digitalWrite(trigPin, LOW); }
duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
} WHERE TO FROM HERE?

This project provides the simplest implementation of an obstacle-


Next, we have five functions relating to motor control. These avoiding robot that we could develop. It serves as a great base
functions, forward(), backward(), turnLeft(), turnRight() will enable to experiment with the code, and build in more intelligence to
the motors to turn on and perform the action as they are called. the system. Currently, it performs a simple sequence based upon
They will continue to be on until you either give the L298N a new a single decision, so what about creating a random decision on
movement command, or you call the stopAll() function. whether it will turn left or right? What about accelerating the motors
up to speed rather than just running them on or off?

void forward() { ACCELERATION CODE:


digitalWrite(IN1, HIGH); // Turn HIGH motor A
digitalWrite(IN2, LOW);
analogWrite(ENA, motorSpeed); for (int x = 0; x < 256; x++)   
{
digitalWrite(IN3, HIGH); // turn HIGH motor B analogWrite(ENA, x);
digitalWrite(IN4, LOW); analogWrite(ENB, x);
analogWrite(ENB, motorSpeed); delay(20);
} }
for (int y = 255; y >= 0; --y)
{

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);

on, the forward() function is called in the loop. delay(20);


}

The “if” statement calls the pingSonar() function, which returns an


integer providing the current distance to any object in front of the
sensor. If the value is equal to or less than the given threshold in the This is a very basic system, using relatively accessible parts. We’ll be
ob_distance constant, it executes a series of commands. The robot building on these fundamentals in future issues, to explore more of
stops, waits 1 second, calls the backward() function, which due to the awesome world that is robotics. ■
the delay will reverse for 2 seconds. It then stops before calling the
turnLeft() function, which makes the left motors reverse while the WANT MORE?
right go forward for 1 second, before stopping again. For more images of SAM or to grab the code,
3D printable files, and so much more visit:
The pingSonar is called again to check the distance before https://diyode.io/003fhsj
continuing forward, reversing and turning again.

diyodemag.com Issue 003 September 2017 63


FEATURE

COLD 12V outlets ar


e provided to
o.

POWER
JASON GREENLOW
Mechanic and lifelong gadget enthusiast
living in Perth, from Christchurch, NZ.
@jason.greenlow

Every time the power goes out, we all think


"I should really build something to provide
backup power". Jason did just that.

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.

64 Issue 003 September 2017 diyodemag.com


FEATURE

It might not be pretty, but it's highly functional.

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.

diyodemag.com Issue 003 September 2017 65


THE CLASSROOM

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

One of the most common components


any maker or student encounters will be
resistors. Resistors come in a huge array of
types and sizes, values, and power ratings.

In an average classroom kit or programmer’s


board like Arduino or Raspberry Pi, the most
commonly found components are the small
signal resistors in the 0.25W-0.5W range

What are resistors, and what does the other


jargon (“metalanguage” for all the educators
out there), actually mean?

66 Issue 003 September 2017 diyodemag.com


THE CLASSROOM

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.

FIXED RANGE OF VALUES

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.

This is the system engineers developed so the percentage gap


between values remains the same. E12 are for 20%, E24 for 10%,
E48 for 5% and so on. The E series is defined by internationally
standards, and not just for resistors. Larger resistors are available, but they are usually hard to find and
well out of the needs range of most of us. In fact, the elements in a
However, some resistors, called ‘High Precision’, are made to a Stove Hotplate or Electric Heater, Electric Hot Water System, or even
specific value for a specific use. In the world of RF, 50 Ohm resistors an Electric Blanket, are resistors.
may be required. So, although most resistors conform to the E12,
E24 or other series, occasionally you might find something different. TOLERANCE
It is unlikely to buy anything other than E24 values at an electronics
shop. The next parameter you will find in a resistor’s description is its
tolerance. This is not always stated, but it is sometimes important,
THE POWER especially to the designer.

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%. ››

diyodemag.com Issue 003 September 2017 67


THE CLASSROOM

›› 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”.

68 Issue 003 September 2017 diyodemag.com


THE CLASSROOM

1 56 x 1000 = 56,000Ω / 56kΩ

1st Digit 2nd Digit 3rd Digit Multiplier Tolerance

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

0.01 10% SILVER

470 X 100 = 47000Ω / 47kΩ

IT’S ALL ABOUT THE COLOUR

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 ››

diyodemag.com Issue 003 September 2017 69


THE CLASSROOM

›› 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

0V Out 0V Out 0V Out


1% 99% 33% 66% 50% 50% GND

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

70 Issue 003 September 2017 diyodemag.com


THE CLASSROOM

A variable resistor may also be used as a rheostat. In the rheostat,


4
a voltage is applied at one end, but the other end is either not
connected, or connected to the wiper. The resistance itself is the
variable value, causing variation in the current passing through it, or
the voltage across the rheostat. V
V V on Top

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

diyodemag.com Issue 003 September 2017 71


PROJECT

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.

72 Issue 003 September 2017 diyodemag.com


PROJECT

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.

Head over to ubuntu-mate.org/raspberry-pi/ and follow the STEP 4: INSTALL NODE.JS


instructions. We're using version 16.04.3 LTS.
Update package manager (always a good idea) and install Node.js
NOTE: There are Linux and Windows tutorials provided to create a libraries.
bootable disk image, on the Ubuntu MATE website. We have created
our own for MacOSX, which you can use if you’re using an Apple
environment. You can check it out at diyode.io/003rqzd. sudo apt-get update
sudo apt-get install -y nodejs
// check everything installed ok:
1 nodejs -v // we’re using v4.2.6

STEP 5: INSTALL NODE.JS PACKAGE MANAGER

This will allow you to easily install modules and packages to use
with Node.js. ››

sudo apt-get install -y npm


npm -version // we’re using 3.5.2

diyodemag.com Issue 003 September 2017 73


PROJECT

›› STEP 6: CREATE THE SIMPLE WEBSERVER APPLICATION STEP 7: HELLO WORLD

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).

sudo mkdir /var/nodeapp && cd /var/nodeapp sudo nano index.js

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();

sudo npm init app.get(‘/’, function (req, res) {


res.send(‘Hello World!’);
});

Install Express.js which is the web framework for Node.js we’re


using. app.listen(3000, function () {
console.log(‘app listening on port 3000!’);
});
sudo npm install express --save

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.

Now you can start the webserver.


cat package.json

nodejs index.js

You should see output similar to the screenshot:

The command line should respond with “app listening on port


3000!”, because we told it to. If it doesn’t, work back through the
code to check for any errors or missed steps. Otherwise, open a
browser to http://localhost:3000/ to see the output [2].

Hello World
2

To stop running the server, go back to the command line and press
Control + C.

STEP 8: COPY CODE FILES AND SETUP

To ensure there are no problems with permissions, you should also


run the following, replacing Ubuntu with your username:

74 Issue 003 September 2017 diyodemag.com


PROJECT

STEP 10: TEST CAPTURE


sudo chown -R ubuntu:ubuntu /var/nodeapp
sudo chmod 755 -R /var/nodeapp On the command line, run the following command:
Note: this is all one line in terminal.

Copy the contents of “EVENT_RECORDER” folder in the resources, to


/var/nodeapp - you can overwrite the original index.js and package. ffmpeg -y -i rtsp://CAMERA_IP_ADDRESS:554/0

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.

sudo ln -s /usr/bin/nodejs /usr/sbin/node


cd /var/nodeapp // ensure you’re in the
right directory

To install all the dependency libraries that are listed in the package. nodejs index // tell node to start the

json file into a node_modules directory, run: server

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].

// Configure your camera for rtsp streaming


3
// our cameras:
// 
camera1 (TECHView):
// rtsp://CAMERA_1_IP_ADDRESS:554/0
// 
camera2 (HIKVISION): There you have it - your system now works!
// rtsp://CAMERA_2_IP_ADDRESS:554/h264.sdp

STEP 12: PERPETUAL OPERATION

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.

diyodemag.com Issue 003 September 2017 75


PROJECT

Fortunately with the inclusion of GPIO, this is a relatively simple


sudo npm install forever -g solution to implement. We will create an example below and we’re
// the -g parameter allows global access going to use a simple push-button switch to trigger recording.
forever start /var/nodeapp/index.js

IMPORTANT NOTE: Hardware interfacing with other devices should


be approached with caution. If you're triggering from a relay output
›› Start this forever script on system startup using Crontab: of some description, then this is usually a safe method as no
voltages are involved other than your own. However if you sent 12V
to your Raspberry Pi, as done from some alarm systems, you could
// replace ubuntu with your username damage your Raspberry Pi. Be careful to ensure high voltages aren't
sudo crontab -u ubuntu -e being sent to your hardware unintentionally.
// select a text editor, 2 for nano then add
PATH=/usr/local/bin:/usr/sbin:/usr/bin/ THE BUILD
@reboot /usr/local/bin/forever start -c /usr/
bin/nodejs /var/nodeapp/index.js Since you may be interfacing your own hardware, this build is
considered as more of a test circuit to ensure everything’s running
as intended. Due to its basic nature, we won’t describe the build
Save and close the file (Control + X, confirm to save). Now your itself. If you’re tackling this project, we’re confident you can follow
system should run in the background with no terminal windows, and the diagram easily.
also start automatically if the RPi is restarted.
PARTS REQUIRED: JAYCAR ALTRONICS
INTELLIGENT RECORDING DURATION 1 x Raspberry Pi 3 XC3630 Z6302B
1 x Tactile Switch SP0609 S1120
The recording duration is also intelligent. While the default 1 x 330Ω Resistor RR0560 R7040
recording duration is 10 seconds, what happens if the GPIO pin is
constantly triggered? If we had simply told the system to record for In addition to the parts list, you’ll require suitable jumper wires and
10 seconds, there’d be no way to interrupt that process. It would breadboard/prototyping equipment.
have to finish the first recording before it began to listen to the GPIO
again. For this reason, we begin recording for an undefined time,
and keep track of the duration. If the GPIO is triggered again, then
we extend the recording duration.

Effectively, if you have an entry that’s being monitored with a


doorway sensor beam, you can trigger recording each time someone
walks through. But if you have someone walking through every five
seconds, for instance, the system will simply record continuously
until there is a 10-second break in people walking through the door.
Of course, this default duration can be set to whatever duration you
like: one minute, one day, one week.

This intelligent recording applies to web browser requests and GPIO


hardware-initiated recording as well.

GETTING FANCY - HARDWARE INTERFACING

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.

76 Issue 003 September 2017 diyodemag.com


PROJECT

On line 16 of index.js you’ll find:


4

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.

REMOTE OPERATION MULTI-CHANNEL RECORDING: As long as your IP camera provides


video in a standard stream that can be interpreted (such as native
While we’ve already provided the callback URLs for triggering MPEG4), and the processor usage is rather low (we saw it sit below
recording, we’ve created a very simple interface. It’s HTML5 using 10% with a single, 1080p full HD stream), you could easily add
offline storage to remember the server IP address, so you don’t have multiple channel functions. It’s important to consider that you don’t
to retype it each time you set it up. want to overload the processor, and you need to retain headroom
in the processor for smooth operation. If you’re recording 1080p
Once this system is running, you can effectively use it as a panic we wouldn’t suggest more than perhaps four streams concurrently;
button, or simply a convenient way to record, using your IP camera. however, if you’re using smaller resolutions this would be less of a
It’s VERY simple. It includes a slider to set the recording duration problem.
and a big record button! [4]
VIDEO TRANSCODING: Further to our previous notes on live
The HTML package is included in the online resources, as a live streaming burden on the Raspberry Pi hardware, some IP cameras
load, and a download so you can modify it. The code will work on may actually require video transcoding to store it in a suitable
any smartphone, tablet, or modern web browser. format. This is processor-intensive and may rapidly overwhelm your
RPi.
It wouldn't take much work to provide the list of recordings, and
the ability to view videos in-browser. However this functionality is DASHCAM: We’re currently experimenting with a dashcam-type
already provided by the Node.JS web server directly, so we would setup with accelerometer and small screen, using the RPi camera.
somewhat be doubling up. We could bundle it all into a neat 3D-printed case! Keep an eye out
for more on this one, in future issues. ■
WHERE TO FROM HERE?
WANT MORE?
LIVE STREAM MONITORING: It is possible to view the live stream To grab the code, load the live HTML, or leave a comment, visit:
from the IP camera directly through a VLC player, which is included https://diyode.io/003xksr
with Ubuntu MATE. We had mixed success with this though.

diyodemag.com Issue 003 September 2017 77


FEATURE

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!

Unmanned Aerial Vehicles (UAVs) are already at the forefront


of commercial minds, solving everything from autonomous
pizza delivery, to tactical operations for defence. CREATE
UNSW have been tackling some of the objectives head on.
We caught up with the team to see what it’s all about.

◄ LEFT
Substantial planning goes into every
build and modification along the way.

78 Issue 003 September 2017 diyodemag.com


FEATURE

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? ››

CROW was designed for the 2017 Land O’lakes Drone


Challenge, where they required teams to be able
to record orthorectified crop images,

CREATE UAS are


taking on the
challenge of creating
intelligent UAVs.

diyodemag.com Issue 003 September 2017 79


FEATURE

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

80 Issue 003 September 2017 diyodemag.com


FEATURE

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 ››

No matter how hard you work,


things don't always go to plan.

diyodemag.com Issue 003 September 2017 81


FEATURE

UAS team looking at flight plans.

›› 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. ››

82 Issue 003 September 2017 diyodemag.com


FEATURE

Attention
UAS have several "learning UAVs" to help
with experimentation and familiarisation.

BOTTOM RIGHT (INSET) ▼


Fine tuning never ends.
Sponsors:
UAV development is an expensive
project, especially when experimenting
with different styles of airframe and
manufacturing processes. Therefore,
CREATE UAS is looking for sponsors who
can provide in-kind or financial support.

By sponsoring CREATE UAS you will have


exposure to potential graduates who
have practical skills with leadership
qualities and technical knowledge that
exceeds the experience and capabilities
of normal students. You will also be
investing in innovative technologies and
ideas that will shape our future. You will
also be part of the development of a
booming industry.

Exposure to local communities will allow


your company to directly market new
products and services, build positive
relationships with the club and the
University of New South Wales, as well as
with other companies that are involved
with the project. Additionally, you’ll boost
your brand awareness through media
exposure and positive word-of-mouth.
To find out more about sponsorship
opportunities with CREATE UAS email
[email protected]
FEATURE

›› Today the UAS team includes 30 undergraduate and masters


students from electrical, mechanical, mechatronics, aerospace,
computer and software engineering, and computer science.

That’s amazing. Thanks for taking us through this epic journey. We


look forward to seeing IBIS take flight! ■

WANT MORE?
For more images, or to discuss this feature, visit:
https://diyode.io/003cbzw

Some of the team with MUGIN.

MUGIN: CROW: IBIS:


(in development)
FLIGHT TIME 110 minutes 65 minutes 120 minutes
One angled target searching One angled target searching
SLANTRANGE 3P - other
IMAGING SENSOR camera and one face down camera and one face down
sensors can be implemented.
optical flow camera. optical flow camera.
Pixhawk with Dual GPS Pixhawk 2 with Dual GPS Pixhawk 2 with Dual GPS
FLIGHTBOARD & NAVIGATION modules - RTK Module set modules - RTK Module set modules - RTK Module set
allows for accuracy of 3-10cm. allows for accuracy of 3-10cm. allows for accuracy of 3-10cm.
WINGSPAN 2600mm 2000mm 2000-2800mm
LENGTH 2000mm 1000mm -
HEIGHT (TAIL TO BASE) 500mm 450mm -
10kg (including aiframe, 3.8kg (including aiframe, 6-8kg (including aiframe,
WEIGHT
electronics and sensors) electronics and sensors) electronics and sensors)
CRUISE SPEED 110km/h 100km/h 120km/h
STALL SPEED 45km/h 48km/h -
MAXIMUM ALTITUDE 1500m 800m 1500m
120km/h for one hour plus 100km/h for one hour plus five Minimum 120km/h for one
ENDURANCE
three minutes of vertical flight. minutes of vertical flight hour.
MTOW 12kg 4.2kg -
520 acres/hr at 20m/s
(assuming one large field and
MAX. DATA RANGE - returning back to base station)
or 5.2 acre to 70 acre fields in
a 2.4km radius at 20m/s

84 Issue 003 September 2017 diyodemag.com


Dream like a child.
Build like a machine.

www.altronics.com.au | 1300 797 007


GOING PRO

3DBRINK Precision mak


es many things
possible.

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.

Stephen was an electronics engineer in the Royal Australian Air


Force (RAAF) but soon moved into robotics and radiometry. The
3DBRINK delta printers were born after countless prototypes and
evolutions. The first thing you’ll notice about these two fantastic
printers is their size - they are BIG! Currently, the smallest model
has a build size of 220(Dia.) x 400(H)mm, while the larger model
is a monstrous 400(Dia.) x 600(H)mm! They’re highly accurate
down to a fine 20micron layer resolution, and they’re powered by a
Raspberry Pi with Touchscreen, and feature an integrated webcam
so you can monitor your printing remotely! We caught up with
Stephen to see how 3DBRINK all came to be.

The 3D printing industry is in a constant state of change. It can’t


be easy to come up with new products for this market, but we’re
constantly amazed at the innovation that’s emerging. What made
you decide to develop your own 3D printer?

RIGHT ►
One of the delta printers.
spberry Pi.
Powered by Ra

86 Issue 003 September 2017 diyodemag.com


GOING PRO

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.

It's always amazing to


see local ideas coming
to fruition.
Manufacturing isn't as strong as it
once was in Australia, but we make
great products. Stephen has put his
knowledge to use to create these
great products, and we wish Stephen
and 3DBRINK the best as the company
leaps from strength to strength.
WHAT THE TECH

MQTT: Machine Queueing Telemetry Transport - a lightweight


messaging protocol using a publish-subscribe model that runs

How
over a TCP-IP network.

BROKER: A device on the network through which all messages


are sent. All client devices need only connect to the broker to
perform their function.

MQTT
CLIENT: A device on the network which connects to a broker. A
client can choose to subscribe, publish or both.

SUBSCRIBE: A client that wishes to receive messages must


first subscribe to a topic, after which the broker will forward
messages relating to that topic.

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.

By monitoring the packets, I found that the mosquitto programs RETAIN


seemed to be using the v3.1 protocol instead of the later v3.1.1,
so I have based the project around this version. The most obvious A flag can be set when a message is sent to the broker for the
difference is in the content of the CONNECT packet. The version message to be “retained”. In this case, any clients connecting or
of the client that operates on the Arduino is also limited to reconnecting will receive the last retained message for a topic.
topic+message lengths of about 125 bytes, because the “remaining Think of this as “last good known value”, where it is better to have
length” field in some packets is encoded as a variable byte length; an “old” value than no value at all. At QoS Level 0 (where there is no
but for values less than 128, this is simply a byte representing the checking that the message is received), using “retain” means that a
number. The three bytes lost between 128 and 125 are due to non- newly connecting client will receive a message immediately instead
message data that takes up space in the “remaining length”. Unless of waiting for another client to publish.
you are actually sending long text-based messages, you should find
that this is sufficient. It would also be the case that much longer TOPIC
messages would quickly eat into the Arduino’s limited memory.
A “topic” can be thought of as a “channel” that a subscribing client
QOS (QUALITY OF SERVICE): can “tune” into. The topic can consist of levels which look like a file
hierarchy, such as house/livingroom/lights, with levels separated by
Three QoS levels are available under MQTT: the “/” character.

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

88 Issue 003 September 2017 diyodemag.com


WHAT THE TECH

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)

Client: Sends SUBSCRIBE packet


Server:  Records the topics the client wants, and then sends a The server responds with a “CONNACK” message, which will look
SUBACK packet something like: ››
Server:  Sends a PUBLISH packet to propagate the message to
subscribed clients.
BYTE VALUE MEANING
If the QoS is greater than zero, further acknowledgments may occur. 1 0x20 CONNACK Packet
2 0x02 2 Bytes Left in Message
A publishing client will simply send a PUBLISH packet as necessary: 3 0x00 Session Present Flag (0x00 Means
Connection Accepted)
Client: Sends PUBLISH packet to the server 4 0x00 Connected Accepted (Other Valyes Indicate
an Error
If the QoS is greater than zero, further acknowledgments may occur.

diyodemag.com Issue 003 September 2017 89


WHAT THE TECH

›› 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

1 0x82 SUBSCRIBE Packet with "SUBACK" Expected


in Reply This is a basic implementation of a QoS level 0 message. Levels 1
2 0x06 6 Bytes Left in Message - Topic Length +5 and 2 have extra overheads such as message IDs, and would also
3 0x00 Message ID MSB expect a response in acknowledgment. To send a message with
4 0x01 Message ID LSB (Value = 1) retain=1, the only difference is that the first byte would be 0x31.
5 0x00 Topic Length MSB
6 0x01 Topic Length LSB (Value = 1) To read a publish message that comes from the server, the stream
7 0x23 # of data is buffered into an array. The first byte is checked to start
8 0x00 Requested QoS on this Topic = 0 with 0x3, and the remainder length and topic length are extracted,
after which the message length and location are extracted, and the
data itself is extracted.
In the MQTT Light Switch project, there is a function that generates
these packets based on topic and ID. The other two packets that are used are the “PINGREQ” (ping
request) and “PINGRESP” (ping response) packets. These are both
The server should respond with a SUBACK packet: simply two bytes each, and serve to let the server and client know
that the connection is working and should be kept alive. The client
sends the “PINGREQ” to the server:
BYTE VALUE MEANING
1 0x90 SUBACK Packet
2 0x03 2 Bytes Left in Message BYTE VALUE MEANING
3 0x00 Message ID MSB 1 0xC0 PINGREQ Packet
4 0x01 Message ID LSB (Value = 1) 2 0x00 0 Bytes Left in Message
5 0x00 QoS Granted

And the server should respond with a “PINGRESP”:


The MQTT Light Switch simply checks if a 5-byte packet has been
received. In practice, the Message ID and QoS should match those
requested. BYTE VALUE MEANING
1 0xD0 PINGRESP Packet
The PUBLISH packet is quite important, and probably the most 2 0x00 0 Bytes Left in Message
complicated for the Arduino, as it is should be capable of sending
and receiving these. Below is an example for sending the “message”
message to the “topic” topic. The function that scans for publish messages is also able to flag
PINGRESP packets, as they occur in the stream of data from the
server, and shows this in the debugging stream in the serial port.
BYTE VALUE MEANING
1 0x30 Public Packed with Retain = 0 MQTT is complex, but we can use it in a simple way, suitable for
2 0x0E 14 Bytes Left - 2+"Topic"+"Message" Arduino tasks. For practical implementation, see our MQTT project
3 0x00 Topic Length MSB elsewhere in this issue! ■
4 0x05 Topic Length LSB (Total 5 Bytes)
5 0x74 "t" GOT SOMETHING TO SAY?
6 0x6F "o" To discuss this edition of What The Tech, visit:
https://diyode.io/003hfkw

90 Issue 003 September 2017 diyodemag.com


PROJECT

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

diyodemag.com Issue 003 September 2017 91


PROJECT

+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

DB1 8 NC CHK +5V


24
DB2 9 NC
320R
DB3 10 NC

DB4 11 A10 ARDUINO


MEGA PASSIVE ZONE
DB5 12 A11
+5V
DB6 13 A12 SIGNAL
34
DB7 14 A13 320R

ACTIVE ZONE +5V


SDA 53
35
SCK 52 SIGNAL
MOSI 51

MISO 50 RELAY OUTPUT


RFID +5V
IRQ NC 28 SIGNAL

GND NC NO COM

RST 49

3.3V 3.3V 29 SIGNAL +5V


ICSP 4

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.

92 Issue 003 September 2017 diyodemag.com


PROJECT

›› RFID CODE LEARNING HOW DOES IT WORK?

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);

sound an alarm if the door is opened. It is currently set for 10 } else {

seconds. You can change this time using the exitDelay variable. To testSystem();

complement this, we have instigated an entry delay. This works in }

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.

diyodemag.com Issue 003 September 2017 93


PROJECT

›› 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();

runs through its normal zone checking code; however, instead of


simply “tripping” if the line is high, the system now checks to see
if this particular zone is contained with the delayZones array. If not The server is initiated during setup and calls the function by
then it trips the alarm. If it is then (depending on entry or exit), it using chkEthernet() which is called from the main loop. This
flags to the system that the alarm is active but that the delay is in function retrieves the URL that is sent to the Arduino from the web
place. Now our issue becomes how do we set a predefined time app. We then go through the CHAR string until we find “?playback”.
delay? We can’t use the delay function as this will halt the main The provided web app simply pushes a single CHAR with each
loop, and the Arduino does not have a time function without the use button press. This could easily be expanded to have more than four
of a real time clock (RTC) module. What we do have is the millis() functions. The code uses “if” statements to look at the CHAR and
function, which will tell us the total number of milliseconds since then run code based on that evaluation.
the Arduino board began running the current program. Using this we
create a timestamp and place it in a variable of type LONG. The code
then continues looping and rechecking the other zones. Once the if (linebuf[15] == ‘D’) {

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”

94 Issue 003 September 2017 diyodemag.com


PROJECT

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.

diyodemag.com Issue 003 September 2017 95


FEATURE

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

Ingenious use of circuit board material,


some clever engineering, a little PIC
code, these badges are WICKED!

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.

96 Issue 003 September 2017 diyodemag.com


FEATURE

Every microamp counts when you’re running from a little battery,


that’s for sure. What were people’s first reactions to the working
badges?

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?

The choice of micro; I’d use something that is supported by the


Arduino IDE so others can modify them easily.

That makes sense - PIC code can be a bit of a pain to programme.


What are you working on now?

It’s long list, which in no particular order includes:

Reflow definitely makes things easier, but it’s quite a skill to


• Multi-channel multi-meter
do it reliably! Aside from a lithium battery and LEDs, what other
• Another IoT Garage Door opener (ESP8266 based, HTML)
components are used to make it work?
• A deluxe version of the Garage Door Opener
that can double as a home watering controller
Resistors and the PIC16F648. Some ‘tricks’ with the PIC were
(ESP8266 based, HTML, CSS, Javascript)
explored, such as internal weak pull-ups.
• “Learn to solder” kits for the kids
• An “Atari Punk” replica and a “LED Colour Mixer” (all analogue)
That’s a really lean component count! There’s a five-way terminal -
• Raspberry Pi “power hat” to control shutdown
is that a programming interface we can see there?
(for use in a RetroPi box)
• WiFi control of “Crossfit Timer” (to replace a lost remote control
Correct.
for my local gym - more ESP goodness, using Bootstrap)

That’s awesome; onboard updates will make for some upgrade


Looking at that list, perhaps I need to focus on “finishing things I’ve
versatility. We can see a bunch of SMD on there - do you have much
started”!
experience with surface mount soldering, and did it present any
challenges?
Many of us can relate to that situation. But hey, who doesn’t
love having 14 projects on the go at once! ■
I’ve been hand soldering SMD for over 15 years now,
but yes, it still presents challenges. 0603 is my
GOT SOMETHING TO SAY?
limit for hand soldering and doing that on a
To discuss this feature, visit:
milled PCB without a solder mask is a chore,
https://diyode.io/003psrw
and it requires lots of desoldering braid. Using
a stencil/paste/reflow I was able to load all 13 ◄ LEFT
boards (I only ordered 10 but Elecrow gave me The back of the badge contains a battery,
PIC micro, LEDs, and power switch.
three bonus boards) in around the same time it
took to hand solder the prototype (give or take a
Coopers Pale Ale!).

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?

MY MILKSHAKE BRINGS ALL THE


DRONES TO THE YARD...

*CLICK* WAIT!

98 Issue 003 September 2017 diyodemag.com


Sink your teeth in.
Raspberry Pi 3 boards and accessories.

www.altronics.com.au | 1300 797 007


Raspberry Pi is a trademark of the Raspberry Pi Foundation.

You might also like