+ All Categories
Home > Documents > Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf ·...

Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf ·...

Date post: 04-Jun-2018
Category:
Upload: hakien
View: 222 times
Download: 0 times
Share this document with a friend
68
Transcript
Page 2: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Cutting Corners, Without Compromise!Compact convenience and economic effi ciency are the hallmarks of our new RDX1 charger. Its space-saving, affordable design fi ts every workbench and budget. This potent AC/DC charger features a backlit 3.2-inch LCD screen and accessible front panel ports for easy charging of all your batteries. Integrated balancing, microprocessor-control, USB functionality and a PC interface combine to make the RDX1 the obvious solution to your charging needs.

FEATURES:• Optimized Operating Software• 10 Battery Memory• Internal Lithium Battery Balancer• Multiple Lithium Battery Charge Modes• Works with Hitec’s “Charge Master” Software• LiPo Battery Meter

SPECIFICATIONS:• AC Input Voltage: 100-240V• DC Input: 11-18V• Charge Power: 60W• Charge Current Range: 0.1 - 6.0A• Max. Discharge Power: 5W• Discharge Current Range: 0.1 - 2.0A• Balancing Port Current Drain: 200MA/Cell

Hitec RCD USA, Inc. / 12115 Paine St. Poway, CA 92064 / 858.748.6948 / www.hitecrcd.com /

Full Page.indd 2 12/6/2016 2:46:47 AM

Page 3: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

(408)748-9600

ea ea ea

Our Full Service Capabilities:

ITAR I SO 9001:2008 UL Approved

Full Page.indd 3 12/6/2016 3:33:52 AM

Page 4: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

4 February 2017

18 An Electronic ChessboardUsing RGB LED Strips and HallEffect Sensors — Part 2Last month’s article finished our chessboard circuit and itsconstruction, and we also looked at how the softwareknows when a piece has been moved and what that pieceis. Let’s wrap things up and create the software needed toaccommodate two players.■ By Theron Wierenga

24 Build Your Own ECG-EKG UnitI find medical instruments like an ECG-EKG unit reallyfascinating. To be able to watch the electronic firingsignals of a heart is mesmerizing and informative. Forparts costing less than $50, I built a unit that plugs intomy laptop computer’s microphone input jack and displaysstunningly clear ECG waveforms.■ By Ron Hoffman

32 Add Sweep Function to Your RFSignal GeneratorAfter I had designed the RF generator (N&V June 2014), Istarted to toy with the idea of adding a sweep function toit. The circuitry is quite economical to build, and draws itspower through a short cable that plugs into a connector atthe rear of the RF generator. Although this unit wascreated for use on my original generator design, the basicarchitecture can be modified for use with commercial RFgenerators that are based on varactor diode tuning.■ By Robert Reed

39 Take a CAN Bus for a Spin —Part 2Recall a Controller Area Network (CAN) bus is designed toallow microcontrollers and devices to communicate witheach other in applications without a host computer. Thisthree-part series will give you the knowledge you need toutilize this protocol. In Part 2, see how to add a CANcontroller to an MCU that lacks one.■ By Jon Titus KZ1G

45 Computer Control andInterfacing with the NI MyRIOPart 3: Controlling Real World Electrical Loads andDevices.Previous installments have demonstrated how to inputfrom a built-in pushbutton and output to a built-in LED,and control these wirelessly from an Apple iPad. Whilethis is a good start into computer control, the “real world”outside of the MyRIO unit typically involves I/O to muchhigher AC and DC voltages and currents than the MyRIOcan tolerate.■ By David Ward

08 Q&AReader Questions Answered HereSee how to construct a visual doorbell, how to drive LEDs,

and discuss text messaging for help.

12 Near SpaceApproaching the Final FrontierTaking Cheap Multispectral Imaging into Near

SpaceSee what happens when

our simple quadcopter

platform is taken to higher

altitudes, and get

acquainted with the results

of taking visible, near

infrared, and long-wave

infrared images in near

space.

50 The Design CycleAdvanced Techniques for Design EngineersSee C More Clearly with the E3mini

The folks at CCS want you to C more clearly. So, they

assembled a very high quality C language training

package. You can train on homebrewed PIC hardware, or

compile and program the supplied C example applications

into a CCS E3mini. We will put the E3mini through its

paces and code up a sensor app using the free C compiler

that is included in the E3mini Board and Book Bundle.

57 Practical 3D PrintingReal World Uses for Electronics ExperimentersMaximite Computer CaseThe original Maximite is a small and versatile single-chip

based computer. I wanted more than just a bare board

sitting on my desk when I was using this retro unit, so I

made a custom case.

Columns

Nuts & Volts (ISSN 1528-9885/CDN Pub Agree #40702530) is published monthly for $26.95 per year by T & L Publications, Inc., 430 Princeland Court, Corona, CA 92879. PERIODICALS POSTAGE PAID ATCORONA, CA AND AT ADDITIONAL MAILING OFFICES. POST MASTER: Send address changes to Nuts & Volts, P.O. Box 15277, North Hollywood, CA 91615 or Station A, P.O. Box 54, Windsor ON N9A6J5; [email protected].

February 2017

06 DEVELOPINGPERSPECTIVESHeirloom Electronics: How

to Build the Very Best

07 READER FEEDBACK16 NEW PRODUCTS

17 SHOWCASE60 NV WEBSTORE62 TECH FORUM64 CLASSIFIEDS65 ELECTRO-NET65 AD INDEX

Departments

Subscription InformationNuts & Volts — PO Box 15277

North Hollywood, CA 91615-9218Call 877-525-2539 or go to www.nutsvolts.comSubscribe • Gift • Renewal • Change of Info

TOC - Feb 17_TOC NV Mar 15.qxd 12/30/2016 2:42 PM Page 4

Page 5: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Toll Free: 1-800-227-7312 Fax: (480) 451-9495www.chaneyelectronics.com Toll Free: 1-800-227-7312 Toll Free: 1-800-227-7312

CHANEYELECTRONICS, INC.

PO BOX 4116, SCOTTSDALE, AZ 85261All Orders Must Include Shipping

Order Online at:

7 in 1 Reusable 9VDC Robotic Lab • Educationalfunandinexpensivetobuildelectronic

robots.• Yougetanacrylicbase,

breadboard,motorsandelectronic componentstobuild7differentrobotactivitiesby reusing thecomponents.

• Greatfirstrobotickitforstudentswithoutpreviouselectronicknowledge.

• Operatesfromone9Vbattery(notincluded).• Sizeofrobotabout5.25”X3.25”X2.75”H.

C7093 $24.95 ea.

3 Watt High Intensity Headlamp• Powerful,lightweightcomfortableheadlamp.• Features 3 Watt white

LED and 3 switchfunctions: high beam,lowbeam,andstrobe.

• Adjustable headbandand ability to pivot indifferentangles.

• Operates on 3 AAAbatteries(notincluded).

G21817 $6.95 ea.

Fascination Star KitProduces an “exploding star” visual effect using 25 LEDs and IC circuitry. Great attention getter for game rooms, discos, etc. Operates from 9V battery (not included). Size of board: 5.25” x 3.5”. Skill Level 3. Requires soldering. C4432 $13.50 ea.

Grab the Gold Game Kit ThisexcitinggamekitfeaturesabrightredLEDpyramidwitha clear LED on top. Whenpowerisappliedeachofthe10LEDslightupinasequencingpattern illuminating its brightorange glow indicating thatyou made it to the top and“pickedupthegold”!Skilllevel2.RequiresSoldering.

C6876 $9.50 ea.

Brilliant 3D White Cube Kit TheBrilliant 3DShimmeringWhiteCubeKit uses 125ultrabright10,000MCDwhiteLEDsthatflashorshimmerdepending on the hidden controlsetting.Thelighteffectsfromthiskitareamazing!Theoutputisabrilliantstrobeflash to a dazzling shimmering effect(dependingonthecontrolsetting).

SkillLevel3.RequiresSoldering. C6919 $30.45 ea.Electro Spinner Kit This amazing kit features abrilliant neon like rainbow ofspinning colors. The ElectroSpinner Kit uses two specialrainbowflashingLED’s,amotorandaspecialelectroniccircuittoproduce attractive and stunningeverchangingringsofneonlikecolors.TheElectroSpinnerautomatically turnsonwhen it is in thedarkandspins foralmostanhourbeforeneedingtoberecharged.SkillLevel2.RequiresSoldering.C6936 $15.35 ea.

3D Shimmering Pyramid KitGiant 3D pyramid shimmers mysteriously to delight and amaze everyone! Uses 75 jumbo red LEDs on a 3 dimensional pyramid that stands over 4’’ tall and has a base of 6’’ x 6’’ x 6’’. Our 3D shimmering pyramid kit features a hidden control to vary the effect from an overall shimmering effect to a sequencing effect. Operates from one 9V battery (not included). Complete with all parts, PC board and instructions. Skill level 3. Requires Soldering.C6437 $26.50 ea.

Electric Slider Learn to Solder Robot KitStand up Electric Slider Learn toSolder Robot Kit features a brightcolorfulsliding,scootingrobot.Uses2powerfulmotorsanda1ICcircuittomove in aweirdpatternonanysmooth surface. Features colorfulflashingLEDswhichmakethiskitarealattentiongettingproject.OverallsizeofPCboardis1.8”x4”.SkillLevel1.RequiresSoldering.

C7012 $10.25ea.

21 in 1 Electronic Discovery Kit The perfect lab for discovering basic electroniccomponentsandelectroniccircuitry.Thiskitconsistsofare-usablenosolderbreadboardand various electroniccomponents including abuzzer,motor,capacitor,CDScell, resistors and LEDs. Notonly do you discover circuitsthat use these components,you’ll also make many funfunctionalprojects.Skilllevel1.Requiresnosoldering.

C7089 $20.50 ea.

Mysterious Sound KitThe Mysterious Sound Kit remainssilent for about 30 seconds afterbeing“armed”(ampletimetohideitinaroom).Afterthe30to40secondtimedelaythetinykitemitsastrangehigh pitched sound for severalsecondsthenaloud“ticking”sound.Skilllevel1.RequiresSoldering.

C7015 $6.15 ea.

(Pkg 5) Tiny Coin Type Pager Vibrator Motor• This coindisk vibratormotor hasa resistanceof

about18Ohm.• Worksonvoltagesfrom1.5VDCupto5VDC.• Sizeonly10mmdia.X3.5mm

thick.• Hastwoshortflexibleinsulated

leadsforpowerconnection.• Comes with peel & stick

mounting surface. Great fortiny“toothbrushhead”robots.

G21112B $10.00 ea.

Mini Open Source Code Logic Board CloneMini USB 5V clone 16M Micro-controller open source code logicboard.Thisboardoperateson5Vlogiclevel,has8analogports:A0-A7,14digitalinput/outputportsRx/Tx.ItusestheAtmelAtmega328P-AUMCU.Hasbootloader installed.Italsohassupportforexternal5Vto12VDCpowersupply.Sizeabout1.75”X0.71”X0.51”.

G21363 $8.00 ea.

SMD IC Star LED Flasher Kit Our most advanced SMDkit uses a tiny 555 SMD ICto flash 5 tiny SMD LEDs.The LEDs flashwith a brightyellow green color. Becausethis kit uses a tiny SMD IC,SMDresistors,atinySMDcapacitor,andSMDLEDs,itprovidesthebestintroductiontoSMDtechnology.Skilllevel3.RequiresSoldering&9Vbattery.C6708 $6.50 ea.

ARD Clone Open Source Logic Board & USB Cable Complete clone open source logicdevelopment board, USB cable andmaleheaderstrip.Greatdevelopmentboard features Amtel ATmega328microprocessorcontroller,supportISPandsketchesdownloadfunction,operationfrom5VDCorUSBinputfromcomputer,14I/OpinswithPWMfunction,digitalI/Oterminals0-13,analogI/Oterminals0-5.Size2.1”X3”.

G21399 $9.95 ea.

66

Merchandise Orders of $40.00or More Can Receive:

FREE!

Digital VOM

Simply Add Stock#NVMETERTo Your Cart

Before Checkout LIMIT 1 coupon per Order

5 Lens Illuminated Head Magnifier • Ourbestperforming,mostcomfortable

illuminatedheadmagnifier.• Powerfulmagnifier

comeswith5interchangeablelenses:1X,1.5X,2X,2.5Xand3.5X.

• Operateson3AG10batteries(alreadyinstalled).

• Lensescomeinare-closeablestorageboxandcanbe“flipped”outofwayeasily.

• GreatforusewithSMDparts,buildingkits,repairingintricateitems.

G21816 $10.95 ea.

Expires April 1st, 2017

Operates on 9V battery

(Not included)

Operates on 9V battery

(Not included)

Operates on 9V battery

(Not included)

Operates on 9V battery

(Not included)

Operates on 9V battery

(Not included)

Full Page.indd 5 1/2/2017 5:14:28 PM

Page 6: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Let’s say you’ve been designing andbuilding electronics devices for

some time now, and you’re good atit. You want to leave somethingbehind — perhaps a gift to a lovedone — that highlights the best of yourwork in the art. Assuming you have acircuit in mind, where do you gofrom here?

Based on my experience usingand maintaining old ham radio gear,high-fidelity audio systems, and testinstruments, both quality build anddocumentation are required for anyelectronic device to survive the testof time. By documentation, I meanincluding the schematic inside thedevice, and not as a separate bookletor computer file. I love maintainingthe old tabletop radios with theschematics pasted to the inside ofthe cabinet. If your device is toosmall to hold the schematic, then foldthe schematic and put it in a plasticpouch affixed to the inside of thedevice. Use a quality cotton-basedpaper in your printer.

By quality build, I mean don’ttake shortcuts in construction. Do usehigh quality standard valuecomponents, and design for ease ofmaintenance. I hate it when I comeacross an old radio or other devicethat relies on glue instead of nuts,bolts, and screws. Adhesive feet aresimple to apply, but after a year ortwo, don’t expect them to still bearound — especially if the device ismoved. Use screw-on feet, even if theenclosure doesn’t come with them.

The enclosure is another oftenoverlooked aspect of a qualitydevice. I love the Hammondextruded aluminum cases. Theycome in a variety of sizes and colors,and it’s easy to order etchedaluminum front and rear panels to fitthe standard sizes. These cases comesupplied with stick-on feet instead ofscrew-on versions, so I simply tossthe adhesive feet and apply my ownscrew-in feet.

Another quality issue is skimpingon sockets and connectors. Go with

gold plated IC sockets, connectors,and switch contacts. Tin contacts willsave you a few cents today, but in 20years, they’ll also cause the newowner headaches.

Power is another issue. I love oldgear that runs on 120 VAC. There’sno scrounging around for a speciallow voltage AC or DC power supplywith a coaxial connector of uncertainsize. There’s also no brick to lose orchance that someone will try adifferent power supply brick that hasa polarity or current rating that’sincompatible with the device. If youdo opt for an external supply, thenmake certain the voltage and currentrequirements — as well as thepolarity and size of the connector —are etched into your creation.

Designing for ease ofmaintenance is as simple as includingtest points on your circuit boards,and allowing generous marginsaround electrolytic capacitors andother devices that will eventuallyrequire changing. A super-compactdesign might impress — as long asthe circuit doesn’t require attention.However, don’t assume that theperson performing the maintenancein the future has your manualdexterity and control of a solderingiron.

Finally, pay attention to theaesthetics of your device. Sure, thespecifications of your super audioamplifier might be impressive, but ifyou want it featured prominently onsomeone’s bookshelf, then it hadbetter look the part. Otherwise, yourdevice might end up in a cardboardbox in the attic or in a yard sale. Forexample, I love the look of oldreceivers. Whether or not theyactually work to specification is ofsecondary importance. Granted,looks aren’t everything, but that’s noexcuse to avoid doing the very bestyou can on the user interface.

So, go ahead, create thatheirloom. Once you’re done,consider sending in a photo to sharewith your fellow readers. NV

Published Monthly By

T & L Publications, Inc.

430 Princeland Ct.Corona, CA 92879-1300

(951) 371-8497

FAX (951) 371-3052

Webstore orders only 1-800-783-4624

www.nutsvolts.com

Subscription OrdersToll Free 1-877-525-2539

Outside US 1-818-487-4545

P.O. Box 15277North Hollywood, CA 91615

FOUNDERJack Lemieux

PUBLISHERLarry Lemieux

[email protected]

ASSOCIATE PUBLISHER/ADVERTISING SALES

Robin [email protected]

EDITORBryan Bergeron

[email protected]

VP OF OPERATIONSVern Graner

[email protected]

CONTRIBUTING EDITORSFred Eady Kristen McIntyreDavid Ward Theron WierengaPaul Verhage Chuck HellebuyckJon Titus Ron HoffmanRobert Reed

CIRCULATION [email protected]

SHOW COORDINATORAudrey Lemieux

WEBSTORE MARKETINGCOVER GRAPHICS

Brian [email protected]

WEBSTORE MANAGER/PRODUCTION

Sean [email protected]

ADMINISTRATIVE STAFFRe Gandara

Copyright © 2017 by T & L Publications, Inc.All Rights Reserved

All advertising is subject to publisher’s approval. Weare not responsible for mistakes, misprints, or typographical errors. Nuts & Volts Magazine assumesno responsibility for the availability or condition of advertised items or for the honesty of the advertiser.The publisher makes no claims for the legality of any item advertised in Nuts & Volts. This is the soleresponsibility of the advertiser. Advertisers and theiragencies agree to indemnify and protect the publisherfrom any and all claims, action, or expense arising fromadvertising placed in Nuts & Volts. Please send all editorial correspondence, UPS, overnight mail, and artwork to: 430 Princeland Court, Corona, CA 92879.

by

Bryan

Bergeron,

EditorDEVELOPINGPERSPECTIVESHeirloom Electronics: How toBuild the Very Best

6 February 2017

Bergeron - Developing Perspectives - Feb 17_Dev Perspectives - ReadFeed Feb15.qxd 12/30/2016 2:47 PM Page 6

Page 7: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Electronic vs. Electric

I just started reading theSeptember 2016 issue and theDeveloping Perspectives column. Iexpected it to deal more with thedefinition of "electronics," but youmostly speak of how to define anenthusiast.

To me, electronics means a setof electronic switches assembledand organized to do a task. The levelof detail of the physics involved isirrelevant.

Whether your electronicswitches are made of transistors,computer chips, or vacuum tubes isirrelevant. Whether you used asoldering iron is irrelevant. Howmany times you have built the sameproject is irrelevant.

If a device contains electronicswitches, it is an electronic device. Ifit uses electrical power, but the onlyswitch is the on/off switch, it iselectrical, not electronic.

For example, a typical electricknife has just one switch. It can beturned on and off. If you're lucky, youmight have a multi-speed knife, whichchanges its speed when youmanually turn or slide a selectorswitch, but this is also an electricaldevice — not an electronic one.

If your knife contains a circuitboard and a keypad where you canpunch in the desired speed, then it isprobably an electronic knife.

This distinction especially bothersme when people refer to electriccigarettes as "electronic." There areno electronic switches inside. Theonly circuit is a simple heatingelement and the only switch is asimple airflow-activated on/offswitch.

Xenophon J. GarciaTempe, AZ

Good that you have time to catchup on your reading. Thanks for thecomments. I agree with you on howelectric has somehow morphed intoelectronic, at least in marketing

Continued on page 64

February 2017 7

- USB- Ethernet- Web server- Modbus- CNC (Mach3/4)- IO

- up to 256 microsteps- 50 V / 6 A

- Isolated

- up to 50MS/s- resolution up to 12bit- Lowest power consumption

- 7 in 1: Oscilloscope, FFT, X/Y, Recorder,

- up to 32 microsteps- 30 V / 2.5 A

- Encoders- LCD

www.poscope.com

READER FEEDBACK

Reader Feedback - Feb 17_Dev Perspectives - ReadFeed Feb15.qxd 12/30/2016 2:49 PM Page 7

Page 8: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

8 February 2017

Q & A n WITH KRISTEN A. McINTYRE

A Visual Doorbell

QI have a relative who is hard of hearing, and I would like to create a circuit that would enable his doorbell button to

light or maybe even flash a table lamp. I have measured the voltage at the doorbell and it reads 16V AC on my meter if that helps with the design.

David CowansWashington, VA

AThis is a great question for me since I’m also hard of hearing. I wear hearing aids, after a somewhat unpleasant series of operations on one of my

ears. By the way, hearing aids are a great thing and have made my life better in many ways. If it’s viable, please encourage your relative to try them. Mine even connect to my iPhone and beam phone calls, music, and podcasts directly into my brain!

Hearing is a very important sense, but one that can be supplemented with visual cues. It should be easy to control a light with the doorbell, but we may need to think a little bit about how to make it effective. I’m going to go through a few designs of increasing complexity to demonstrate how I think about problems like this.

The naive approach is to just take the doorbell signal and rectify it so we can use it as a control signal. The

rectification doesn’t have to be efficient, but just enough to be able to sense the state of the button. Controlling some other thing in the house (like a lamp) can be done with either a traditional mechanical relay or with a more reliable solid-state relay. Let’s assume it’s going to be something connected to the AC mains.

An example of this first approach is shown in Figure 1. In this case, we just rectify the bell signal, and hope we have enough current / power available to switch a relay. That probably works just fine. We choose a 24V coil because the peak voltage for 16V RMS AC is 16 x √2 = 22.6V. There’s a slightly more sophisticated approach shown in Figure 2.

We take the AC signal, pump charge into a capacitor with a bleed down resistor, and then switch a transistor.

That buffered signal is the control for some kind of relay (a mechanical relay is shown). Note the snubber diode used to keep the relay coil’s inductance from destroying the control transistor when the relay is turned off. A solid-state relay won’t require this.

You will need a power supply for this second approach, of course, and it needs to be isolated from the doorbell. Most wall warts are isolated. The doorbell signal could be further

isolated with a small 1:1 transformer, though that’s not shown in the figure.

While both of these approaches work at some level, the light would only be on for the period of time that the doorbell button was pushed. Ideally, we’d like to extend that. To do that, we want to add some asymmetry to the charge going into and out of the capacitor. This is one of the reasons that I chose to use a transistor to buffer energizing the relay. So, let’s extend things a bit so that the light stays on for a while by using a transistor to quickly pump the capacitor up, and then use a resistor to bleed it down at a slower pace.

While the transistor used to pump up the capacitor is not strictly necessary, it’s a hedge against how much power is available from the doorbell signal. The time constant is set to about two seconds in this example, but by changing the R and C values, it can be extended. This approach is shown in Figure 3.

The last thing would be to make it flash. That requires a few more transistors, so we can add an oscillator. While an NE555 could be used, it might be about the same amount of work to just apply some discrete devices and learn something too! We’ll use an astable multivibrator that we can power up and use that to drive the relay (Figure 4). Now, I’ll admit that I haven’t simulated or tested these circuits, but I’ll bet they’re pretty close. It might flash at around 2 Hz, but try it and see.

Since a project like this involves connecting the relay to the AC mains, caution is advised. Dealing with higher voltages is always a bit risky. Make sure the AC is disconnected when testing the circuit and insulate the connections as much as possible. Most of the circuit can be troubleshot without connecting the mains.

On Driving LEDs

QI have built a 4 x 4 x 4 LED cube shield kit given to me as a birthday gift. Each of its blue LEDs is powered

directly from a high Arduino pin (pins 0 to 15) to a low pin (16 to 19) without

QUESTIONS and ANSWERSPost comments on this article and find any associated files and/or downloads at

www.nutsvolts.com/magazine/article/February2017_QA.

In this column, Kristen answers questions about all aspects of electronics, including computer hardware, software, circuits, electronic theory, troubleshooting, and anything else of interest to the hobbyist. Feel free to participate with your questions, comments, or suggestions. Send all questions and comments to: Q&[email protected].

• A Visual Doorbell• On Driving LEDs• Text Messaging When in Need

n FIGURE 1. Simplest doorbell control.

n FIGURE 2. More sophisticated active control.

McIntyre - Q&A - Feb 17.indd 8 1/2/2017 10:39:16 PM

Page 9: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

February 2017 9

rectification doesn’t have to be efficient, but just enough to be able to sense the state of the button. Controlling some other thing in the house (like a lamp) can be done with either a traditional mechanical relay or with a more reliable solid-state relay. Let’s assume it’s going to be something connected to the AC mains.

An example of this first approach is shown in Figure 1. In this case, we just rectify the bell signal, and hope we have enough current / power available to switch a relay. That probably works just fine. We choose a 24V coil because the peak voltage for 16V RMS AC is 16 x √2 = 22.6V. There’s a slightly more sophisticated approach shown in Figure 2.

We take the AC signal, pump charge into a capacitor with a bleed down resistor, and then switch a transistor.

That buffered signal is the control for some kind of relay (a mechanical relay is shown). Note the snubber diode used to keep the relay coil’s inductance from destroying the control transistor when the relay is turned off. A solid-state relay won’t require this.

You will need a power supply for this second approach, of course, and it needs to be isolated from the doorbell. Most wall warts are isolated. The doorbell signal could be further

isolated with a small 1:1 transformer, though that’s not shown in the figure.

While both of these approaches work at some level, the light would only be on for the period of time that the doorbell button was pushed. Ideally, we’d like to extend that. To do that, we want to add some asymmetry to the charge going into and out of the capacitor. This is one of the reasons that I chose to use a transistor to buffer energizing the relay. So, let’s extend things a bit so that the light stays on for a while by using a transistor to quickly pump the capacitor up, and then use a resistor to bleed it down at a slower pace.

While the transistor used to pump up the capacitor is not strictly necessary, it’s a hedge against how much power is available from the doorbell signal. The time constant is set to about two seconds in this example, but by changing the R and C values, it can be extended. This approach is shown in Figure 3.

The last thing would be to make it flash. That requires a few more transistors, so we can add an oscillator. While an NE555 could be used, it might be about the same amount of work to just apply some discrete devices and learn something too! We’ll use an astable multivibrator that we can power up and use that to drive the relay (Figure 4). Now, I’ll admit that I haven’t simulated or tested these circuits, but I’ll bet they’re pretty close. It might flash at around 2 Hz, but try it and see.

Since a project like this involves connecting the relay to the AC mains, caution is advised. Dealing with higher voltages is always a bit risky. Make sure the AC is disconnected when testing the circuit and insulate the connections as much as possible. Most of the circuit can be troubleshot without connecting the mains.

On Driving LEDs

QI have built a 4 x 4 x 4 LED cube shield kit given to me as a birthday gift. Each of its blue LEDs is powered

directly from a high Arduino pin (pins 0 to 15) to a low pin (16 to 19) without

any current-limiting resistors. It works fine! Pins 14 to 19 are also pins A0 to A5. The Arduino sees a 16 x 4 matrix. The Arduino must put five volts across the LEDs. Why are they surviving this treatment?

I do understand that they are only being flashed on very briefly. My friendly expert says that the Arduino cannot supply enough current to damage the LEDs. Is he right? Can I power an LED between (say) pin 0 high and

QUESTIONS and ANSWERSPost comments on this article and find any associated files and/or downloads at

www.nutsvolts.com/magazine/article/February2017_QA.

• A Visual Doorbell• On Driving LEDs• Text Messaging When in Need

n FIGURE 3. Doorbell control with asymmetric timing.

McIntyre - Q&A - Feb 17.indd 9 1/2/2017 10:39:40 PM

Page 10: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

10 February 2017

pin 17 low indefinitely without damage to the LED or Arduino? How many LEDs can the Arduino power like this without damage?

Ray Marston’s excellent article “PRACTICAL LED INDICATOR AND FLASHER CIRCUITS” that was included in a recent Nuts & Volts content newsletter explains that other colors of LEDs have lower forward voltages (Vf). Will these survive the same treatment? The article also mentions that LEDs will only resist a limited reverse voltage. I’m pretty sure the “off” LEDs in the cube see a reversed five volts during the cycle. Does this not load the Arduino? What are the limits of this behavior?

If this is okay, why do we bother with current-limiting resistors in other circuits?

Mike O’Hagannear Aberdeen, Scotland, UK

AWell Mike, I think that you and your friendly expert mostly guessed the right answer. I had to dive into the Atmel 328 datasheet — a representative example of one of the

processors used on Arduino boards — to see what the digital pins look like electrically.

First, let me state that current limiting is important for LEDs. These devices act like diodes in most respects, except that their forward voltage is generally higher than signal or rectifier diodes, and they have a low reverse breakdown voltage. They also have a somewhat ‘mushy’ V-I curve, so the current comes on more slowly with voltage. Too much current through these devices will cause the die to heat and eventually destroy the device.

Laser diodes typically take much more current, meaning there is much more power dissipated. Note that some of that power escapes the device as light, but most of it is just heat. Some LEDs and laser diodes have built-

in heatsinks and heat conduction pads for keeping the die cool. We really want to keep that die as cool as we can.

Getting back to the Arduino, I’ve reproduced part of the equivalent circuit for an Arduino digital pin in Figure 5. What you can see is that while the part of the circuit that is the output driver does not have a limiting resistor, the pull-up portion does. The equivalent resistance of that pull-up circuit is about 25K ohms. Even if there are no resistors at all, the current is limited by the ability of FETs in the driver to source and sink current. However, the resistor in the pull-up circuit (from the FET source / drain to the pin) makes that more deterministic and significantly limits the current.

Looking at the Arduino spec, the specified output current per I/O pin is 20 mA. No doubt that’s the driver’s limit. That’s enough to light up an LED to a reasonable brightness, but not enough to damage it. Since the drivers are current-limited (most transistors look like current sources when they’re not saturated), the voltage across the LED will rise until the driver cannot supply more current. The voltage will then settle there, roughly at the LED’s typical forward voltage.

LEDs with differing forward voltages will not matter all that much since the driver will be acting as a current source. The actual voltage across the LED should again settle to around its forward voltage as the driver current limits.

So, what we see is that we can drive one I/O pin high and another low to light up a particular LED in a square matrix. By cycling them rapidly, we can fool the eye into thinking that they are on steadily. Of course, individuals have different lower frequencies where they start to see the flashing. This is called the flicker-fusion rate, and my personal rate is quite high, meaning that I can often see this flashing, even when the rate is quite fast.

n FIGURE 4. Doorbell control with oscillator.

When we do this as a matrix, we end up reverse biasing LEDs as well. Therefore, they must have a reverse voltage that is at least 5V. It’s surprisingly hard to find specs on the reverse voltage for modern LEDs. There are hand waving mentions that it’s at least 5V, but probably higher. Datasheets do not list this characteristic. In this case, all I can do is hand wave too and say, it’s probably just fine at only 5V.

As for steady operation with the LED on, that should be no problem with 20 mA being supplied. Most LEDs can take even more current than that, but it depends on the individual LED. If you think that current is too high, you can, of course, add a separate current-limiting resistor. The resistor value will depend on the desired current, the driver’s capabilities, and the forward voltage.

Text Messaging When in Need

QI am disabled with MS and spinal stenosis, and I fall a lot. I bought a remote control FOB with a receiver that will give me a real contact closure. My goal is to find/construct a device that can

text messages to my neighbors when I need help.Mark Hoffman

n FIGURE 5. Simplified Atmel / Arduino I/O pin.

McIntyre - Q&A - Feb 17.indd 10 1/2/2017 10:40:00 PM

Page 11: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

February 2017 11

in heatsinks and heat conduction pads for keeping the die cool. We really want to keep that die as cool as we can.

Getting back to the Arduino, I’ve reproduced part of the equivalent circuit for an Arduino digital pin in Figure 5. What you can see is that while the part of the circuit that is the output driver does not have a limiting resistor, the pull-up portion does. The equivalent resistance of that pull-up circuit is about 25K ohms. Even if there are no resistors at all, the current is limited by the ability of FETs in the driver to source and sink current. However, the resistor in the pull-up circuit (from the FET source / drain to the pin) makes that more deterministic and significantly limits the current.

Looking at the Arduino spec, the specified output current per I/O pin is 20 mA. No doubt that’s the driver’s limit. That’s enough to light up an LED to a reasonable brightness, but not enough to damage it. Since the drivers are current-limited (most transistors look like current sources when they’re not saturated), the voltage across the LED will rise until the driver cannot supply more current. The voltage will then settle there, roughly at the LED’s typical forward voltage.

LEDs with differing forward voltages will not matter all that much since the driver will be acting as a current source. The actual voltage across the LED should again settle to around its forward voltage as the driver current limits.

So, what we see is that we can drive one I/O pin high and another low to light up a particular LED in a square matrix. By cycling them rapidly, we can fool the eye into thinking that they are on steadily. Of course, individuals have different lower frequencies where they start to see the flashing. This is called the flicker-fusion rate, and my personal rate is quite high, meaning that I can often see this flashing, even when the rate is quite fast.

When we do this as a matrix, we end up reverse biasing LEDs as well. Therefore, they must have a reverse voltage that is at least 5V. It’s surprisingly hard to find specs on the reverse voltage for modern LEDs. There are hand waving mentions that it’s at least 5V, but probably higher. Datasheets do not list this characteristic. In this case, all I can do is hand wave too and say, it’s probably just fine at only 5V.

As for steady operation with the LED on, that should be no problem with 20 mA being supplied. Most LEDs can take even more current than that, but it depends on the individual LED. If you think that current is too high, you can, of course, add a separate current-limiting resistor. The resistor value will depend on the desired current, the driver’s capabilities, and the forward voltage.

Text Messaging When in Need

QI am disabled with MS and spinal stenosis, and I fall a lot. I bought a remote control FOB with a receiver that will give me a real contact closure. My goal is to find/construct a device that can

text messages to my neighbors when I need help.Mark Hoffman

AMark, I’m really sorry to hear about your condition and falling. That must be very difficult. Thinking about a system like this, I think it’s a nontrivial project involving

something like an Internet-connected Raspberry Pi and some kind of client that will send the text message over a TCP connection to a service provider.

While this would make a great construction article, it’s probably beyond the scope of Q&A. Generally, I try to give solutions to specific questions and provide some of the theory behind what I’m doing. Writing up the design on an entire project is what other writers for Nuts & Volts are so good at. (And one of those authors could be any one of you who read this column.)

That aside, however, I’m hesitant to advise you to do this on your own. This is almost a medical device, and reliability is a key aspect of medical devices. I would hate to think of you trying to use such a homemade device and having it fail to work properly just when you needed it most. As it turns out, there are many services out there that will do this for you. At one point, I had such a device for my mother before she moved into assisted living. They work very well and have reasonable range. NV

McIntyre - Q&A - Feb 17.indd 11 1/2/2017 10:47:16 PM

Page 12: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Since amateur radio operatorshave been sending near

spacecraft skyward, there’s beenamateur science imaging of Earth andits resources. The resources imagedfrom near space include naturalresources like forests and rivers, andartificial ones like roads and cities.Until now, however, a huge portionof that imaging was done in visiblefrequencies using film, and latelydigital imagers. With the advent of

thermal imagers and easilymodified digital cameras,the spectral range open toamateurs has increasedtremendously.

Along with that expansion, theinformation gleaned has expandedalso. This article will briefly describethe Imaging BalloonSat and thenshow some of the images it returnedover three near space missions. Withluck, I’ll find additional ways to

expand the spectral rangeof the images returned inthe near future.

Constructing theImagingBalloonSat

To make imagingpractical for any nearspace mission, I decided tocreate a BalloonSat whosesole purpose was to carry

and operate several cameras. Thecameras I described last timeincluded long-wave infrared (a SeekReveal thermal imager), near infrared(a modified Mobius Action Camera),and an inexpensive digital camera.It’s important that they’re rigidlymounted inside the airframe and easyto access for their SD memory cards.I decided this time to create aframework inside the BalloonSatairframe to hold the cameras and thatcould be removed between missions.

My solution consists of aCoroplast (corrugated polypropyleneplastic) frame and a Styrofoam shell.The flight computer, battery pack,and cameras attach to the Coroplastframe, and then the frame slides intoa Styrofoam shell for protection from

Last time, we discussed testing simplemultispectral imaging from a quadcopterplatform. This time, you’ll see whathappens when it’s taken to higheraltitudes, and get acquainted with theresults of taking visible, near infrared, andlong-wave infrared images in near space. Ifind these missions return a lot of eyecandy and I hope Nuts & Volts readerswill enjoy the scenery as much as I have.

■ BY L. PAUL VERHAGENEAR SPACE

Taking Cheap Multispectral Imaginginto Near Space

12 February 2017

[email protected]

The Coroplast frame packed with three imagers, a flightcomputer, and battery pack. The four AAA battery pack ismounted to the left wall and the flight computer to the top. Theimagers (from left to right) are an inexpensive Vivatar digitalcamera, Seek Reveal thermal imager, and a Mobius ActionCamera modified for near infrared.

I built the Imaging BalloonSat shown hereto carry three imagers into near space.They include long-wave infrared, near

infrared, and visible. The images returnedexceeded my expectations and point the

way to further experiments.

Verhage - Near Space - Feb 17_Near Space - Aug 15.qxd 12/30/2016 2:56 PM Page 12

Page 13: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

the cold of near space. Two boltssecurely hold the Coroplast frameinside the Styrofoam shell during themission, and two rubber bands holdthe Styrofoam hatch in place to theshell.

After recovery, I can remove thebolts and then pull the Coroplastframe from the Styrofoam shell. Withthe frame free, it only takes two boltsto remove all three cameras. It onlytakes two bolts because the thermalimager is held in place by two plasticand foam rubber fingers.

The imaging BalloonSat needed

to be flown sooner than I planned, sothe actual operation of the imagerswasn’t as complete as I had hoped.Instead of operating all three camerasfrom the flight computer, I justoperated the Vivatar and Seek Revealfrom it, and the Mobius wasprogrammed to take stills every 10seconds. The flight computer used itsrelay to take visible images and aservo to take thermal images.Meanwhile, the Mobius took picturesindependently of the flight computer.In a future upgrade, I’ll connect theshutter switch of the Mobius to a

relay and operate it the same way asthe Vivitar camera.

Flying the ImagingBalloonSat

I made several flights carryingcomponents of the ImagingBalloonSat before a full-on attemptlast November. What follows aresome of the results from these flightsand an explanation of what theyshow. I’m looking forward to onemore upgrade to integrate all theimages together. Meanwhile, please

APPROACHING THE FINAL FRONTIER

Post comments on this article and find any associated files and/or downloads atwww.nutsvolts.com/magazine/article/February2017_NearSpace_Multispectral-Imaging.

February 2017 13

Another thermal image from the first near spaceflight to carry a long-wave IR imager. This picture

shows Lake Lowell in thermal infrared. Notice howmuch cooler the lake is compared to the farm and

open lands around it. The bright yellow patches areopen desert, which heat up faster than the irrigated

fields. This image was taken at an altitude of81,700 feet.

An image from my first near space flight tocarry a long-wave IR imager (thermalimager). I didn’t have a digital camera onthis flight, so I am comparing the thermalimage to the Google Earth image. Thewarmest locations (those in yellow) are bareland — there’s no farming taking place there.The coolest regions are in purple and theyare well watered farm fields. There’s astructure, probably a storage barn thatregisters as cold compared to thesurrounding field. The Snake River has asurface temperature of 61 degrees and iscooler than the island in the picture. Notethat the eastern side of the island or theriver along this bank is very cool. Since thiswas taken at sunrise, this edge of the islandmay still be in the shade. This image wastaken at an altitude of 9,500 feet.

This image shows the boundary between the Owyhee Mountains and theTreasure Valley. These are dry desert mountains and therefore show up in warm

yellow because the dry grassland warms up rapidly in the morning sunlight. Thered streak in the mountains is a valley that’s sheltered from sunrise. Left of the

mountains (or to the northwest) is farmland. The grid pattern of private farmland can be made out. This image was taken at an altitude of 94,400 feet.

Verhage - Near Space - Feb 17_Near Space - Aug 15.qxd 12/30/2016 2:56 PM Page 13

Page 14: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

enjoy this eye candy from near space.

Next StepsI need to modify the Mobius one more time and get

the digital camera working before the Imaging BalloonSatcan operate at full capacity. Then, it will be able to returnimages in long-wave infrared, near infrared, and visible. Ihave a lead on ultraviolet filters and am waiting until I canput away a little more money to justify purchasing it.

Even without an ultraviolet imaging capability, I planto re-launch the BalloonSat and compare images taken inthe summer and fall to those taken in winter. Readersshould plan on seeing more this next year.

Onwards and Upwards,Your near space guide NV

14 February 2017

This image taken at 72,000 feet is located south ofNampa, ID. It shows a view of Lake Lowell and howwater doesn’t reflect infrared. To the upper right ofthe image (north, in this case) are the lawns ofNampa. The properties are much smaller than thefarms, so this makes the image appear moregranular than the farms south of town. Numerousislands can be seen in the Snake River.

This image illustrates the ability of infrared topenetrate atmospheric haze. At 63,000 feet, we

see the boundary between the OwyheeMountains and the Treasure Valley. Erosion from

the Owyhee Mountains is visible in the centerof the image. It appears there may be a few

parallel fault lines running left and right in theOwyhee Mountains — especially on the right

side of the mountains. The Snake River and itsvalley runs left and right across the image.

Above the Snake River is farm land. Farms withcrops appear bright white because their

chlorophyll reflects infrared. So, harvestedfarmland — without any plants left — appearsdarker. Pivot irrigation is obviously popular for

large farms. This image was recorded nearWalter’s Ferry.

This image of Earth’s horizonwas taken at 60,000 feet duringdescent; at this altitude, thedistance to the horizon is 300miles. Very little detail of theground is visible because thereis such a huge difference intemperature between theground and space. Oneobservation that can be made isthat the atmosphere appears tohave two layers based ontemperature. I don’t believe thiscan represent the boundarybetween the troposphere(bottom layer) and stratosphere(next higher layer). The reason isthat the stratosphere’stemperature increases withaltitude and in this image, thehigher layer appears to beuniformly cooler than thebottom layer.

Verhage - Near Space - Feb 17_Near Space - Aug 15.qxd 12/30/2016 2:56 PM Page 14

Page 15: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Looking northeast towards Boise, ID from 38,000feet. This image was recorded during descent as the

Imaging BalloonSat swung back and forth. Boiseabuts the Boise Mountain range. At this altitude,

the horizon is 240 miles away and in infrared;details all the way to the horizon remain sharp. Gasmolecules in the atmosphere do not scatter infrared

light (like they scatter blue light). So, the skyappears very dark nearly to the horizon. It appears

there are snow-capped mountains visible at theupper right horizon. If so, they could be over 200

miles away. In the lower right (south in this image),the city of Boise gives way to open desert.

The highest near infrared image was taken at92,000 feet. There’s a large patch of open rangeland in the upper right, or west. A large and wellirrigated farm within this open land is visible. Thenatural variation in desert plant growth is alsovisible as irregular darker patches might be aresult of grazing. Several islands are visible inthe Snake River, along with a wider canyon-likeregion in the bottom right. The large and rounddepression in the top center is actually a butte.

eddedARM.c.embwwwomputC

omeddedARM.cduleon-M

er-omputC

ptimizw OoN

duleoon-Mer-

:ored fptimiz

-4900ST

e Optionoruad CQooth Enabledi & BluetiFW

eescale i.MX6 ARM CPUrFemancorffoerigh PH

(480) 837-5200

/uco.tsteeS

(480) 837-5200

or Detailsff/uc

February 2017 15

Verhage - Near Space - Feb 17_Near Space - Aug 15.qxd 12/30/2016 2:57 PM Page 15

Page 16: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

NEW PRODUCTS■ HARDWARE■ SOFTWARE■ GADGETS■ TOOLS

COMBO PACKSENERGYPROPELSYSTEMS

Hitec’s Energy Propel motors arenow available in convenient

combination packs. With built-inprogrammable speed controls andhigh performance efficient motors,the Energy Propel line delivers thefunctionality and space-saving design

multirotor projects require. Eachbundle pack comes with twoclockwise and two counter-clockwisemotors to fully equip a rotorcraft andget it airborne quickly. Pricing beginsat $121.88 and the combos areavailable in six sizes.

16 February 2017

PATTERN PLATES

FROM 2.25”-12”Actobotics’ new pattern plates are identical to

a single side of the Actobotics channel(hyperlink to channel). These plates are anexcellent addition to an extensive buildingsystem as they allow you to box in yourchannel for added strength; build in space-limited areas; and save weight and costwhere the strength of a full piece ofchannel is not a necessity. Pricingranges from $1.39-$3.99.

CLAMPING

D-HUBSServoCity’s clamping D-hubs are a noteworthy solution

for transferring power from a shaft to a hub. Whileconventional clamping hubs with a cylindrical bore relysolely on clamping force to keep the hub from slipping onthe shaft, these new D-hubs have a D-shaped bore toperfectly match a D-shaft of the same diameter.

This means that even without tightening the pinchbolt, the hub is prevented from slipping on the shaft. The

6-32 pinch bolt (when tightened)will tighten the hub around the D-shaft for added security, and tokeep the D-hub from sliding up

and down the shaft. Price is $6.99.

SET-SCREW

D-HUBSNew set screw D-hubs from ServoCity also offer

a solution for transferring power from a shaftto the hub. While conventional hubs with a cylindricalbore rely solely on the set screw to keep the hub fromslipping on the shaft, the new D-hubs have a D-shapedbore to perfectly match a D-shaft of the same diameter.This means that even without a set-screw, the hub isprevented from slipping on the shaft.

The 10-32 set-screw, when tightened, will applypressure to the flat of the D-shaft for added security andto keep the D-hub from sliding up and down the shaft.Since the set screw contacts the flat of the shaft, it makesremoval of the hub very easy — no marring of thecylindrical surface which would interfere with theinstallation/removal of parts such as ball bearings. Price is$5.99.

For more information, contact:

ServoCitywww.servocity.com

New Products - Feb 17_Mar15 -NV - NewProducts.qxd 12/30/2016 2:59 PM Page 16

Page 17: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Motor features include:• Motor and ESC combination

provides a lightweight andspace-saving alternative toseparate components.

• High performance, efficientmotor.

• Programmable speed control.• Updatable firmware.• BLHeli featuring active

braking/damping light.• ONE SHOT synchronization

protocol for fastercommunication between theflight control and ESC.

• Simple wiring eliminates failurepoints.

• Backed by Hitec’s one yearwarranty.

For more information, contact:

Hitec RCD USA, Inc.www.hitecrcd.com

ARBITRARYWAVEFORM

GENERATORRIGOL Technologies, Inc., has

announced the expansion oftheir waveform generator portfolio.The new DG1022Z gives budgetconstrained customers anuncompromised solution withadvanced features typically reservedfor much higher price points.

Makers, educators, and IoTdesigners working with bothelectrical and RF applications canbuild long complex arbitrary waves,generate eighth order harmonics,create advanced modulations, andinject random noise. RIGOL isdelivering this advanced unit for$359.

With 25 MHz max sine waveand square wave frequency, two fullfunction independent channels,exceptionally long Arb memorylength, and 160+ built-in waveforms,the RIGOL DG1022Z brings theaward winning capabilities of theDG1000Z family down to the valuemarket. Customers with limitedbudgets will no longer need to workaround their equipment’scompromised functionality becausethe DG1022Z delivers:

• 25 MHz Sine/25 MHz squarewave frequency

• Two full function independentchannels

• Eighth order harmonicgenerator

• AM, FM, PM, ASK, FSK, PSK,and PWM modulation

• 2 Mpts Standard memory(16M optional)

• SiFi sampling technology forimproved signal fidelity

• Built-in seven-digit counter• +160 Standard waveforms

The DG1022Z extends theDG1000Z portfolio to three models(25, 30, and 60 MHz), providing thesame unprecedented value at eachpoint. With the introduction of theDG1022Z, RIGOL will also reducethe price of the existing DG1022 tojust $299.

Stock Drive ProductsSetting Ideas Into Motion

EXPLOREDESIGNBUY ONLINE

One-Stop Shop for

Setting Ideas Into MotionStock Drive ProductsSetting Ideas Into MotionStock Drive Products

One-Stop Shop forMEXDEBU

wno minimum requirement

For more information, contact:

RIGOL Technologieswww.rigolna.com

If you have a new product thatyou would like us to run in ourNew Products section, pleaseemail a short description (300-500 words) and a photo of yourproduct to:[email protected].

February 2017 17

Continued on page 56

New Products - Feb 17_Mar15 -NV - NewProducts.qxd 1/2/2017 9:44 PM Page 17

Page 18: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

18 February 2017

BUILD IT YOURSELF

Last month's article

finished with the

chessboard circuit

and its construction.

Also presented was

how the software

knows a piece has

been moved and

what piece it was.

Now on to the

software needed to

take two players

through a game of

chess.

By Theron Wierenga

An Electronic ChessboardUsing RGB LED Strips and

HALL EFFECTSENSORS

Aflow chart of the Teensy 3.1 loop() function isshown in Figure 1. The mainLoop() functioncontains the majority of the functionality of

the chessboard program; a simplified flow chart of itappears in Figure 2.

The mainLoop() function processes three possiblelegal moves for each turn:

1. A piece moves to a legal empty space.2. A piece is picked up, but is just returned to its

original location.3. A piece captures an opponent’s piece.

The mainLoop() function starts by simply looking fora piece that has been removed from the board. Here isa code fragment:

int total1 = 0, total2 = 0, total3 = 0; // For different reads of total number of pieces // on the board

do{

total1 = readHall(piecesTemp1); // Read the Hall Effect sensors

}while (total1 == bdCount); // Wait for a change

The readHall() function returns the total number ofpieces found on the board, which is compared to thecurrent board count bdCount. Next, the temporaryarray pieceTemp1 is compared with piecesCurrent

Part 2

■ FIGURE 1. Flow chartof the Teensy 3.1 loop().

Wierenga - LED Chess - Feb 17 - Part 2_Blank Project NV.qxd 12/30/2016 3:02 PM Page 18

Page 19: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

which holds the current piece array. ThecomparePieceArrays() function does this. It simplyloops through all 64 board positions until it findsthe square that doesn’t match and then writes thisinto xx and yy, which are variables passed byreference. Whatever variable passed to xx and yywill now have the position in the array of the piecethat was removed.

This function is a good example of the codenot being efficient, but instead being easy tounderstand. It wades through possibly all 64 boardsquares to find the changed piece. In return for this,the code structure is easy to comprehend — a looplooking for non-matching numbers:

// Compare piece arraysbool comparePieceArrays(int &xx, int &yy, bytepiecesCurrent[][8], byte piecesTemp1[][8]){

for (int y = 0; y < 8; y++){

for (int x = 0; x < 8; x++){

if (piecesTemp1[y][x] != piecesCurrent[y][x]){

// First piece that doesn’t match // previous,// Write to xx, yy and returnxx = x; yy = y;return false;

// arrays are different}

}}return true; // arrays are the same

}

After some error checking (such as this squarecontaining a piece of the correct turn, i.e., color),the next thing needed is to find the path (the list ofsquares) that this piece can move to legally. This listconsists of three arrays — pathX[ ], pathY[ ], pathVal[ ] —and pathCount; the latter keeping track of how manysquares are stored in the arrays. The function that storesthe squares — getPaths() — is very lengthy as it needs to beable to find the different legal paths for all the differentpieces.

The chess pieces group themselves into two distinctmethods to obtain the paths. The bishop, rook, and queencan all slide across the board in straight lines: eitherperpendicular as the rook, diagonally as the bishop, orboth as the queen. So, for example, the queen’s paths arefound by:

// Queen ***************************** Queen Queen Queen if ((val == BLACK_QUEEN) || (val == WHITE_QUEEN)){

// x and y are the starting positionsgetSinglePathinPaths(x + 2, y + 2, 1, 1, pathCount, turn);

getSinglePathinPaths(x + 2, y + 2,-1,-1, pathCount, turn);getSinglePathinPaths(x + 2, y + 2, 1,-1, pathCount, turn);getSinglePathinPaths(x + 2, y + 2,-1, 1, pathCount, turn);getSinglePathinPaths(x + 2, y + 2, 1, 0, pathCount, turn);getSinglePathinPaths(x + 2, y + 2,-1, 0, pathCount, turn);getSinglePathinPaths(x + 2, y + 2, 0, 1, pathCount, turn);getSinglePathinPaths(x + 2, y + 2, 0,-1, pathCount,turn);

}

The function getSinglePathinPaths() is called eighttimes; once for each direction it can move. Note that thethird and fourth parameters of this function are either 0, 1,or -1. These values are added to the queen’s x and yposition in a loop, depending on the perpendicular ordiagonal direction in which the piece can move.

When the loop hits a square that is not empty, itchecks to see if the piece there is an opponent’s and if so,

February 2017 19

Post comments on this article and find any associated files and/or downloads at www.nutsvolts.com/magazine/article/February2017_Electronic-Chessboard-LEDs-Hall-Effect-Sensors-Part-2.

■ FIGURE 2. Flow chartof the mainLoop()

function.

Wierenga - LED Chess - Feb 17 - Part 2_Blank Project NV.qxd 12/30/2016 3:02 PM Page 19

Page 20: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

stores it in the path as well, and then returns from thefunction. If it wasn’t an opponent, it was either one of itsown pieces or off the board. Note that the count variableis passed by reference, so that it keeps an ongoing total ofthe number of squares stored in the arrays when thegetSinglePathinPaths() function is called multiple times.

The code for the bishop’s and rook’s paths containonly four calls to getSinglePathinPaths() for the variousdirections they can move:

// Follow a single path to its endvoid getSinglePathinPaths(int xx, int yy, int xdir, intydir, int &count, int turn){

// This function starts with the xx, yy position of a // square and xdir and ydir directions to add// to the square’s position with every loop. The loop // continues as long as the squares are EMPTY. // When it hits a square occupied it checks to be // sure it is an opponent’s piece and then will // add this to the path.

xx = xx + xdir;yy = yy + ydir;while (piecesValCur[yy][xx] == EMPTY){

pathY[count] = yy - 2; pathX[count] = xx - 2; pathVal[count] = piecesValCur[yy][xx];count++;xx = xx + xdir;yy = yy + ydir;

}if (((turn == WHITE) && (piecesValCur[yy][xx] >= BLACK_PAWN) && (piecesValCur[yy][xx] <= BLACK_KING)) ||

((turn == BLACK) && (piecesValCur[yy][xx] >= WHITE_PAWN) && (piecesValCur[yy][xx] <= WHITE_KING)))

{pathY[count] = yy - 2; pathX[count] = xx - 2; pathVal[count] = piecesValCur[yy][xx]; count++;

}}

Finding the paths for the knight is a different mattersince it can jump to a possible eight different positions.A brute force method is used here, and a similartechnique is used for the king. The pawn uses morecomplex code because of its different movements. Theeight relative moves of the knight are stored in the i[ ]and j[ ] arrays, which are then just added to the startingposition in a loop. If the square has an opponent’spiece in it or if it is empty, the square is stored in thepath array:

// Knight *********************** Knight Knight Knightif ((val == BLACK_KNIGHT) || (val == WHITE_KNIGHT)){

// x and y are the starting positionsint i[8] = {1, 2, -1, -2, -1, -2, 1, 2};int j[8] = {2, 1, -2, -1, 2, 1,-2,-1};// Check all eight possible movesfor (int k = 0; k < 8; k++)

{xx = x + 2 + i[k]; yy = y + 2 + j[k];if (((turn == WHITE) &&(piecesValCur[yy][xx]>=BLACK_PAWN) && (piecesValCur[yy][xx]<=BLACK_KING)) ||

((turn == BLACK) && (piecesValCur[yy][xx]>=WHITE_PAWN) && (piecesValCur[yy][xx]<=WHITE_KING)) ||(piecesValCur[yy][xx] == EMPTY))

{pathY[pathCount] = yy - 2; pathX[pathCount] = xx - 2; pathVal[pathCount] = piecesValCur[yy][xx];pathCount++;

}}

}

Details for all the pieces can be found in the completeprogram (available at the article link). After the path for apiece is stored, it is displayed on the chessboard. I chosegreen to color the squares that are empty and yellow for asquare that has an opponent’s piece that can be captured.The Boolean true in the colorSquare() function’s parameter

20 February 2017

■ FIGURE 3.Determiningif the king is

in check flow chart.

Wierenga - LED Chess - Feb 17 - Part 2_Blank Project NV.qxd 12/30/2016 3:02 PM Page 20

Page 21: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

list will turn on each square’s color as it proceeds throughthe loop of squares to count in the path:

// Color the positions a piece can legally move tovoid colorPath(int count, int turn){

for (int i = 0; i < count; i++){

if (pathVal[i] == EMPTY) colorSquare(pathX[i], pathY[i], colors[GREEN], true);

if ((turn == WHITE) && (pathVal[i] >= BLACK_PAWN) && (pathVal[i] <= BLACK_KING))

colorSquare(pathX[i], pathY[i], colors[YELLOW], true);

if ((turn == BLACK) && (pathVal[i] >= WHITE_PAWN) && (pathVal[i] <= WHITE_KING))

colorSquare(pathX[i], pathY[i], colors[YELLOW], true);

}}

The function to determine if a king is in check is alittle more difficult conceptually. It is necessary to look atthe paths for pieces in the next turn. So, if it is the WHITEturn, then it looks at the paths for all the BLACK pieces tosee if the WHITE king is in the path of a BLACK piece. Ifthe program finds the king in check, it colors the square ofthe king and the piece placing the king in check violet.Figure 3 is a simplified flow chart followed by thecomplete kingInCheck() function:

// Is the King in check ?bool kingInCheck(int turn){

// This one is tricky, we go though entire array // looking for the next turn’s pieces// Then we find the paths for the next turn’s pieces // and if the turn’s king// is on one of these paths then that king will be in// check. We color the square// with the piece that puts the king in check violet.pathCount = 0;for (int y = 0; y < 8; y++){

for (int x = 0; x < 8; x++){

if (((turn==WHITE)&&(piecesValCur[y+2][ x+2]>=BLACK_PAWN)&&(piecesValCur[y+2]

[x+2]<=BLACK_KING)) ||((turn==BLACK)&&(piecesValCur[y+2][x+2]>=WHITE_PAWN)&&(piecesValCur[y+2][x+2]<=WHITE_KING)))

{getPaths(piecesValCur[y + 2][x + 2], x, y, nextTurn(turn));for (int i = 0; i < pathCount; i++){

if (((pathVal[i]==BLACK_KING)&& (turn==BLACK))||((pathVal[i]==WHITE_KING)&&(turn==WHITE))){

lcd.setCursor(0, 4);

if (turn == BLACK){

lcd.print(“Black King in Check”);}else {

lcd.print(“White King in Check”);}// Save the position of the king in // checkxKingCheck = pathX[i]; yKingCheck = pathY[i];// Save the position of the attacking // piecexAttackPos = x; yAttackPos = y;pathToKingInCheck(xKingCheck, yKingCheck,xAttackPos, yAttackPos);colorSquare(xAttackPos, yAttackPos, colors[VIOLET], true);colorSquare(xKingCheck, yKingCheck, colors[VIOLET], true);pathCount = 0;return true;

}}pathCount = 0;

}}

}return false;

}

The checkMate() function was the most challengingportion of the software to write. In order to achievecheckmate and win the game, the king must be placed in

February 2017 21

It should be pointed out that if you intentionally try tofool the chessboard by doing something far outside therules of chess — like picking up multiple pieces andswitching them — it is not too hard to confuse theprogram or even lock it up. The software will do a good bitof checking to look for reasonable errors, but it cannotidentify every trick you try. This should not present aproblem if you simply stick to the rules of chess. Thiswould not be the case if each piece could identify itselfuniquely.

For this, it would be necessary to have something likean RFID tag on each chess piece and an RFID reader thatcould scan all 64 positions. A barcode reader might beanother approach to this. The difficulty here is building a64-position reader that will only detect and identify thepiece above it.

When a piece is captured, the user should first removethe capturing piece, then remove the captured piece andthen replace the capturing piece on the captured piece'ssquare. If you use the capturing piece to slide or knockover the captured piece, you will most likely get an errorwhich may not be recoverable, as the magnets can triggerother Hall-effect sensors.

If you try to take two turns in a row or place a pieceon a square which is not allowed, or make a move thatplaces your king in check, all the LEDs on the board willturn red, indicating an illegal move. When you return theoffending piece to its original position, the board willrevert to blue and red squares and play can continue.

Wierenga - LED Chess - Feb 17 - Part 2_Blank Project NV.qxd 12/30/2016 3:02 PM Page 21

Page 22: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

check, and on the next move the kingmust not be able to get out of check.Looking at the reverse, in order to notbe in checkmate after the king hasbeen placed in check, the king must:

1. Be able to move out of thepath of the attacking piece and notinto check from another of theopponent’s pieces.

2. One of the king’s pieces canblock the move of the attackingpiece.

3. The attacking piece can becaptured by one of the king’s pieces.

Figure 4 is a simplified flowchart of checkMate() which isfollowed by the function code:

// Are we in checkmate ? return // true if in checkmatebool checkMate(int turn){

// Function kingInCheck has // stored king position in // xKingCheck, yKingCheck, and // also stored xAttackPos and // yAttackPos of attacking piece.// pathToKingInCheck(xKingCheck, // yKingCheck, xAttackPos, // yAttackPos) stores the path // between the two in int // variables xPathtoKing[6], // yPathtoKing[6], and // pathtoKingCount

// can the king move to get out // of check// get the paths for the king // which is in checkgetPaths(piecesValCur[yKingCheck + 2][xKingCheck + 2], xKingCheck, yKingCheck, turn);printPaths(xKingCheck, yKingCheck);// pathtoKingCount needs to be zeroed before // returning this functionfor (int i = 0; i < pathCount; i++) // paths king can move to{

for (int j = 0; j < pathtoKingCount; j++) // attack path to king{

if (!((pathX[i] == xPathtoKing[j]) && (pathY[i] == yPathtoKing[j]))){

// There is a square the king can move to that // is not on the path from the attacking piece // to the king, but will king move into check // from another piece?myDebug(pathX[i], pathY[i], “Path king can move to”);

if (squareInOpponentPath (pathX[i], pathY[i], turn)){

// this square will have // king in check if // king moves there continue;

}else{

// square is open - no // checkmate

pathtoKingCount = 0;pathCount = 0;return false;

}}

}}

// now we check to see if we can // move a piece to block // attacking piece

for (int y = 0; y < 8; y++){

for (int x = 0; x < 8; x++){

if (((turn == BLACK) && (piecesValCur[y + 2][x + 2] >= BLACK_PAWN) && (piecesValCur[y + 2][x + 2] <= BLACK_QUEEN)) ||

((turn == WHITE) && (piecesValCur[y + 2][x + 2] >= WHITE_PAWN) && (piecesValCur[y + 2][x + 2] <= WHITE_QUEEN)))

{pathCount = 0;getPaths(piecesValCur[y + 2][x + 2], x, y, turn);// printPaths(x, y);for (int i = 0; i < pathCount; i++)

{for (int j = 0; j < pathtoKingCount; j++){

if (((pathX[i] == xPathtoKing[j]) &&

(pathY[i] == yPathtoKing[j])) ||

// piece can move to attacking path((pathX[i] == xAttackPos) && (pathY[i] == yAttackPos)))

// or can capture the attacking piece{

// we can block attacking piecemyDebug(pathX[i], pathY[i], “Blocking piece for king”);pathtoKingCount = 0;pathCount = 0;return false;

}}

22 February 2017

■ FIGURE 4. Flowchart of checkMate()function.

Wierenga - LED Chess - Feb 17 - Part 2_Blank Project NV.qxd 12/30/2016 3:02 PM Page 22

Page 23: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

}}

}}pathtoKingCount = 0;// if we get here, checkmatelcd.setCursor(0, 4);lcd.print(“ CHECKMATE! “);return true;

}

Future EnhancementsThroughout the Teensy 3.1 chess program, there are

many lines that print to the serial monitor of the ArduinoGUI with the USB cord in place. These could beeliminated from the program or commented out, but havebeen left in place as they were helpful when debugging,and will be informative to a user in understanding how theprogram is operating. A number of functions were alsowritten that simply print information to the serial monitorfor debugging, such as printPaths(), printPiecesLoc(),printPiecesVal(), and myDebug(). If you want to modify thisprogram, you should find these functions useful.

A possible enhancement to the existing code mightbe suggesting moves to each player. Changing theprogram to have the computer play against a personwould require a major effort. The computer used for thiscould be the Teensy 3.1, or a PC could be interfaced tothe chessboard. Surprisingly, the Teensy 3.1 only uses12% of its program space and 10% of its dynamicmemory for the software presented here, so there is lotsof room for additional code.

This project has given me a lot of satisfaction, and isone of those where adding possible additions to the codewill be a challenging and interesting activity.

It’s your move now. NV

February 2017 23

■ FIGURE 5. Testing the chessboard.

■ FIGURE 6. The LED chessboard on a wood tablemade by my son.

Wierenga - LED Chess - Feb 17 - Part 2_Blank Project NV.qxd 12/30/2016 3:02 PM Page 23

Page 24: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

24 February 2017

BUILD IT YOURSELF

I find medical instrumentslike an ECG-EKG unitreally fascinating. To beable to watch theelectronic firing signals ofa heart is mesmerizingand informative. Thepatterns tell you, forexample, if you havearrhythmia (irregularrhythm or beat), too littleor too much potassium inyour blood, ischemia (alack of blood flow to theheart muscle), damagedheart muscle (after a heartattack), fibrillation (whenthe heart just quivers anddoesn’t fully pump), yourheart rate, and muchmore. For the rest of thisarticle, I will refer to theunit as an ECG (Electro-Cardio Gram).

Build Your Own

ECG-EKGUNIT

By Ron Hoffman

Post comments on this article andfind any associated files and/or

downloads at www.nutsvolts.com/magazine/article/February2017

_Build-ECG-EKG-Unit.

If you’ve ever had an ECG at your doctor’s office, the bill for itcan run anywhere from $100 for a standard three-lead test to$1,200 for a 12-lead test. Being an engineer and inventor, I

wanted to see if I could come up with a really good low cost wayof designing and building my own unit so I could check out myown heart signals. The effort was fraught with design trial anderror, and many lessons to be learned along the way. The resultwas better than I ever imagined.

For parts costing less than $50, I built an ECG unit that plugsinto my laptop computer’s microphone input jack and displaysstunningly clear ECG waveforms. It uses a single quad RRIO (rail-to-rail, input-output) op-amp and features a red LED that blinks witheach heartbeat.

This project is easy to build and can be used to explore thefascinating field of electrocardiography. There are many lessons tobe learned from the design and the methods used in this project.

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 24

Page 25: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

How theCircuitWorks

The schematicdiagram (Figure 1)shows the MCP6024quad op-amp which isthe “heart” of the unit.U1A and U1D areconnected as acommon referenceddifferentialinstrumentation op-amp. This means that ifthe +Vin and -Vin inputvoltages are equal, theoutput voltage will bethe same as thereference voltage. TheMCP6024 is the quadRRIO op-amp. Theinput is linear from Vss-.2V to Vdd+.2V. Three AAA batteries (4.5 volts) providethe supply voltage to the MCP6024.

To maximize the voltage swing, the amplifier bias (orreference level voltage) is set by R11, R12, and U1C. Thevalues selected give a reference voltage of 2.25 volts orVdd/2, which is roughly half of the linear range. Theoutput of U1C is the “ground” reference for the unit, andis connected to the output jack, the case ground, and thecommon Smith electrode. It also serves as the positiveinput reference for U1A and U1D — the two op-ampsused as the common mode referenced differentialinstrumentation amplifier. The green LED shows if thepower is on and the relative health of the batteries.

There are many topologies for circuits that do thesame thing. I chose the ground referenced dual op-ampinstrumentation topology for a couple of reasons. First, itminimizes the parts count, and “ground” references theoutput. In this case, the ground is the Vdd/2 output ofU1C, which allows the output to swing above and belowthe common ground, and allows for the unit to “float” atthe level of the display device whether it is anoscilloscope, laptop computer, tablet, or smartphone. Theminimum number of op-amps used by this topologyallows the fourth unused op-amp to be connected as acomparator to flash a red LED when a heartbeat occurs.

The second reason for using this topology is that itprovides a simple way to adjust the CMR (Common ModeRejection) of noise introduced at the inputs from theelectrodes attached to the patient. This noise is due to RFsources, sparking motor brushes, but mostly from 60 HzAC line noise induced from wiring in a building.To reduce

the input noise while providing high gain amplification tothe differential heart signals, two circuit techniques areemployed. One is the CMR; the other is low pass filtering.In this design, the filtering is done at the input to theinstrumentation op-amps, and at the output before it’sdelivered to the display device. R1-R2 and R3-R4 formdivider networks that provide bias voltage to the + inputsof U1A and U1D, and limits the input from the patient’selectrodes.

Potentiometer R10 allows for the two dividernetworks to be balanced exactly to cancel out anycommon mode input signals. It is designated as CMR2. Toassist and filter the input, C5 connects the + inputs of U1Aand U1D. If you take the parallel impedance of R1 and R2(about 800K) times 2 (for R3 and R4), and design for a lowpass cutoff around 50 Hz, it yields about 2 nF. Using thenearest standard value, 2.2 nF, Fo= 1/(2*pi*Rtot*C5) yieldsa low pass frequency of 45.44 Hz.

While we are discussing the inputs, C3 and C4 are veryimportant. The RC time constant for the input is 220 nF *4.9 Mohms = 1.08 seconds. Any signal occurring in .1seconds will pass through easily. Any DC voltage will beblocked. This is very important. It turns out that theelectrodes and the acids on your skin act as tiny batteries.They create differential voltages that will be amplified andrun the output to saturation which buries the heart signal.By connecting the third Smith electrode, this gives thepatient a “common” reference which greatly reduces noiseand improves the common mode rejection. Capacitors C3and C4 pass the heart signals but block the electrodeinduced DC voltages. Thus, the output stays near the

■ FIGURE 1. Schematic diagram.

February 2017 25

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 25

Page 26: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

common reference ground, and full gain of the heart signalsis obtained. R13 and C6 provide for a second low pass filterat 48 Hz prior to the signal passing to the display device.

In addition to R10 (CMR2) which is used to balancethe input divider network, an additional CMR1 adjustmentis made via R8. Potentiometer R8 adjusts the CMR of U1A

and U1D by balancing the ratio of R9 and R5, whichfurther improves the overall CMR of the circuit. R7 inseries with potentiometer R6 allows the gain to beadjusted from approximately 900 to 4,200. The neededgain is between 2,000 and 3,000. This is dependent uponthe type of electrodes used, area prep (alcohol swabs toclean oils and dead skin from electrode area), thickness ofpatient’s skin, level of subcutaneous fat, patient’s physicalsize, etc.

Op-amp U1B is used as a comparator to flash the redLED D2 whenever the QRS complex (heartbeat signal) isobserved. Potentiometer R16 adjusts the thresholdreference of U1B; the -input of U1B connects via R15 tothe output of U1D. Adjusting R16 to a couple of tenths ofa volt above the common causes U1B’s output to behighand LED D2 off. Whenever the heartbeat is detected, theQR portion of the signal goes to nearly one voltdepending on the amount of gain, etc., causing U1B to golow and flash LED D2.

Author's Note: If a smoother waveform is desired, C5could be increased to 4.7 nF or 10 nF, to provide a breakfrequency of 20 Hz or 10 Hz, respectively, to reduce

noise. Likewise, increasing R13 to 33Kwould reduce the output breakfrequency to 22 Hz, further smoothingthe waveform noise.

Building theUnit

The Parts List includes the numbersand sources for all of the parts neededto build the unit. Also provided (at thearticle link) are the Gerber files for theprinted circuit board (PCB). I built my unitusing a RadioShack 276-147 general-purpose PCB. The Gerber file checkprint (Figure 2) was used to place thecomponents and wire wrap wire toconnect any parts that were too farapart to use the part leads to make theconnection.

Also, since the PCB I designed wastwo-sided, the wire wrap allowed me tocross over wires and make connectionsthat wouldn’t have been possible onthe single side of the board (seeFigures 3 and 4).

Resistors R1- R3 and R5-R9 need tobe matched in value. It doesn’t matter ifthe value is lower or higher than onemeg, just that they match within onedigit, i.e., 2@994K, or 2@1003K. Thesame applies for R2-R4 — [email protected] [email protected] — just so they match. The

26 February 2017

■ FIGURE 2. PCB layout.

■ FIGURE 3. Top side of PCB.

■ FIGURE 4. Bottom side of PCB.

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 26

Page 27: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

rest of the values are not critical.Be sure to use metal film 1% resistors where

specified. Carbon 5% resistors can be used for therest of the circuit. Be sure to check all your wiringand definitely use the 14-pin socket for theMCP6024 so you can replace it if needed. Check allthe ohms between pins against the schematic beforeapplying the battery, and then check the plus inputof U1C (pin 10) compared with ground. It shouldread about 2.25 volts. The voltage across C1 shouldread about 4.5 volts; higher for new batteries, lowerfor used batteries. If that all checks out, turn thepower off and install the MCP6024, being careful toobserve the pin 1 placement. If you turn it around180 degrees, you will fry it upon applying power.

I printed multiple copies of the label fileavailable at the article link and used one for the drill andfiling guide on the enclosure (Figure 5).

Align a label equidistant from the sides and ends ofthe aluminum “U” channel (top). Tape it in place on foursides. Use a 9/64” drill bit for all the holes. Drill twoholes in the slide switch rectangle and file out to thelines. Next, two holes need to be drilled on each side ofthe aluminum U channel. Each hole needs to be 1/2”above the bottom of the side flange.

Drill the electrode input jack and the output (ScopeOut) jack hole using a 15/64” drill bit (for a tight fit) or1/4”drill bit. The output jack should be below the ScopeOut on the label. The electrode input jack should beabout 1.75” from the front of the unit.

Building the electrode cable assembly is next. Thegoal was to make it simple to connect the cable to theunit using low cost parts. That is why the standardminiature stereo phone plug and jack were selected.

Cut a piece of two-conductor 28 gauge C1228 Carolcoaxial cable about five to six feet long. Slide the plugcover over the wire before stripping and soldering thewire to the 1/8” phone plug. Solder the red wire to thephone plug tip lug; solder the black to the ring lug and theground wire to the sleeve crimp lug. Crimp the groundwire around the cable jacket, then slide the plug coverover the plug and screw it tight.

Strip the other end of the cable jacket about .75” fromthe end. Strip 1/4” of insulation from the red and blackwires. Leave the ground wire, but remove the aluminumfoil wrap. Cut three 18” lengths of Carol C1156 RG174/U50 ohm coaxial cable. Remove 1” of the jacket on oneend of each cable. Push the braided sheath toward thejacket. Using a right angle dental probe, carefully separatethe braided wires and pull the center conductor throughthe opening.

Stretch the braided sheath out. Strip 1/4” insulation offof the center conductor. Slide a 1/2” length of 1/8”diameter heat shrink tubing over the conductor. Solder thestripped center conductor to the red conductor; slide the

heat shrink tubing over the soldered wires; then apply heatto shrink the tubing over the solder joint. Repeat thisprocedure for the black wire.

Last, solder together the ground shields from the threecoaxial cables and the center conductor of the Smithelectrode cable to the ground wire of the two-conductorcoax cable (see Figure 6). Next, place a 4” length of 1/4”diameter heat shrink tubing over the three coaxial wiresand slide it over the soldered joints and their heat shrinktubing. About 1.25” should cover the two-conductor coaxwire. Apply heat to shrink the tubing tightly into place,securing the three coaxial leads to the two-conductorcoaxial cable.

Finally, strip about 3/8” from the center conductor ofeach cable and tin the wire with solder. Trim the braidedground shield off. Slide the outer insulation sheath so that itcovers all of the ground wire’s braided shield. Insert thecenter wires of the coaxial cables into the electrode clampsthat attach to the adhesive electrodes.

To do this, disassemble the electrode clamps bysnapping off the housing, then remove the actuator lever.This releases the upper spring clamp. Remove the bottommetal strip from the clamp. Thread the center conductorinto the slot in front of the spring clamp and replace themetal strip into the housing; then snap it in place. Placethe upper spring clamp and replace the actuator lever.

Last, snap the top housing cover over the lever on tothe clamp housing. Use a small jeweler’s screw driver topress the coaxial cable to the side of the clamp housing,wedging it under the rib. Fill the end of the clamp housingwith hot melt glue to strain-relieve the coaxial cable and hold

February 2017 27

■ FIGURE 5. Label used as drill guide for machiningenclosure.

■ FIGURE 6. Cable assembly connection.

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 27

Page 28: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

it in place. Finally, measure the resistance from the tip of the1/8” phone plug to one of the electrode clamps and markit with a “+” sign.

Measure the resistance from the ring contact of thephone plug to another of the electrode clamps and mark it

with a “-” sign. The last clamp should be labeled with a “C”for common. Make sure that there are no shorts betweenthe different clamps. The final assembly should look likeFigure 7.

Use another copy of the label and laminate it for theECG unit. After cutting out the label, laminate it withFellows self-adhesive laminating sheets, leaving about a1/4” border around the edge. It works best if you leaveabout a 1/2” border around the edge of the label.

After you burnish the laminating sheet to the label, cutthe holes out for the trim pot adjustment, switch actuator,and LEDs using an Xacto™ knife. Now is the time to trim

the edge of the laminate to leave the 1/4” borderaround the label. This corrects for any skewedalignment when laminating the label and providesequal and straight borders around the edge for aprofessional looking result.

When all the holes are cut out and you have dry-fitted the label to the unit, make sure that all theholes line up properly. Remove the laminate sheetbacking, and carefully align and mount the label tothe enclosure (Figure 8). It may help to hold thealuminum up or back light the enclosure as youlower the label and align the holes with theenclosure. Burnish the label edges to insure thelabel seals well.

The PCB is mounted to the enclosure using four4-40 x 5/8” (preferred) or 3/4” (easier to find)machine screws, four 4-40 by 1/4” nylon threadedspacers, and four 4-40 nuts. Place the machinescrews through the label, screw on the threadedspacers, and tighten. Mount the PCB on themachine screws and secure with four 4-40 nuts(Figure 9).

Solder the red lead of the AAA battery pack tothe V+ pad or the double soldered pins of the slideswitch, and solder the black battery pack lead tothe V- pad (Figure 9). At final assembly, a block offoam rubber packing can be used to prevent thebattery pack from moving.

Finish the electrical assembly (Figure 10) by

28 February 2017

■ FIGURE 9. PCB installed.

■ FIGURE 10. Final assembly connections.

■ FIGURE 7. Finished cable assembly.

■ FIGURE 8. Laminated label applied to enclosure.

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 28

Page 29: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

connecting some 24 gauge hookup wire from the circuitboard to the output phone jack (white, common, tosleeve lug closest to aluminum enclosure; red, from R14,OUT, to the tip lug, closest to the common lug).

Cut a 4” piece of two-conductor coaxial cable (CarolC1228). Prepare one end by removing 3/4” of the outerjacket. Then, remove the aluminum shield foil, leavingthe ground wire.

Strip 1/8” insulation from the red and black wires.Prepare the other end of the cable the same way, butremove 1.5” of the outer jacket. Solder the shorter cableend ground to the common sleeve lug closest to thealuminum enclosure; the red lead to the tip lug next tothe common lug; and the black lead to the ring lug.

Solder the other end of the cable to the PCB.Ground to S.E.; red lead to In+, C3; and black lead to In-,C4. Figure 11 shows the finished ECG unit, the 1/8”stereo patch cord, and the three-clamp electrode cableassembly.

February 2017 29

■ FIGURE 11. Finished unit.

QTY. REF SOURCE DESCRIPTION/VALUE

1 C1 Digi-Key 470 μF alum elec, 16V, Panasonic, ECEA1CN471U, DK# P1170-ND or equiv.(DK)

4 C2, C3, DK .22 μF metalized poly, ±10%, PanasonicC4, C6 ECQ-V1H224JL, DK# P4667-ND or equiv.

1 C5 DK 2.2 nF metalized poly, ±10%, PanasonicECQ-V1H222JF, DK# P4555-ND or equiv.

1 D1 DK LED, GRN (green), Lite-On LTL-4232N or equiv., DK# 160-1143-ND1 D2 DK LED, RED (red), Lite-On LTL-4222N or equiv., DK# 160-1140-ND4 R1, R3, DK 1 meg resistor, 1/4W, 1%, metal film, YAGEO, 1.00MXBK-ND or equiv.

R5, R92 R2, R4 DK 3.9 meg resistor, 1/4W, 1%, metal film, YAGEO, 3.90MGACT-ND or equiv.1 R6 DK 5K, .5W linear trimpot, COPAL ELECT. CT6EP502-ND or equiv.3 R7, R17, DK 470 ohm resistor 5%, YAGEO, 470QBK-ND or equiv.

R181 R8 DK 10K, .5W, linear trimpot, COPAL ELECT. CT6EP103-ND or equiv.1 R10 DK 100K, .5W linear trimpot, COPAL ELECT. CT6EP104-ND or equiv.2 R11, R12 DK 10K resistor, 1/4W, 1%, metal film, YAGEO, 10.0KXBK-ND or equiv.1 R13 DK 15K resistor 5%, carbon film, YAGEO, 15KQBK-ND or equiv.1 R14 DK 1.0K resistor 5%, carbon film YAGEO, 1.0KQBK-ND or equiv.1 R15 DK 10K resistor 5%, carbon film YAGEO, 10KQBK-ND or equiv.1 R16 DK 50K, .5W linear trimpot, COPAL ELECT. CT6EP503-ND or equiv.2 S1, S2 DK SPDT miniature slide switch, STS121PC04, 450-1609-ND1 U1 DK MCP6024-I/P quad RR op-amp, MICROCHIP MCP6024-I/P-ND2 J1, J2 DK 3.5 mm, stereo phone jack, CUI, INC., CP1-3533-ND1 Enclosure DK Aluminum box, 5.5 x 3.0 x 1.25", LMB HEEGER, INC., L200-ND1 Bat Hldr Mouser Three AAA battery holder w/leads, EAGLE, MSR# 12BH431-GR3 AAA Batteries1 PCB RadioShack RadioShack #276-147, 3.5" x 2.4"1 6' Cable DK Carol 1228, Two-conductor, 26AW G, foil with ground, DK# C1228-50-ND3 18" Cable DK Carol 1156, 50 ohm, coax cable, RG174/U 26AW G, DK# C1156-50-NDMISC. Fellows laminating sheets4 Screws #4-40 x .75" machine screws for mounting PCB in enclosure4 Nuts 4-40 machine screw nuts4 Stand-offs DK 1/4"/4-40, hex-threaded nylon spacer, DK# 1902-AK-ND100 Tab/snap NIKOTABS, NIKOMED USA, INC.

electrodes10 Contact RongRui-century Science and Technology, Inc., multi-function electrode adapter,

clamps REZ013-M

PARTSLIST

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 29

Page 30: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Adjusting and Using theECG Unit

Set all of the trim pots to their center position. Standthe U channel upright in the slot of the base as shown inFigure 12. Download and install the Zietnitz SoundcardScope app (version 1.46). Connect the ECG unit, SCOPEOUT, to the microphone input of a laptop computer usinga short stereo 1/8” to 1/8” patch cable/cord. Connect theinput cable to the ECG unit.

Open the settings tab of the Soundcard Scope app.Set the scope input to the external microphone (Figure13). Adjust the channel 1 amplitude to 400m per division.Set the trace time to five seconds. Set the trigger amplitudeto 200 mV. Adjust the ECG pre-amp gain pot to the 2:00 or3:00 position between the center and max gain setting (this

yields roughly a gain of 2,000).Connect the red and black input leads together and

hold them with your fingers. Adjust CMR2 until the scopetrace is a minimum amplitude. Adjust CMR1 until there isa minimum amplitude. The unit is now ready for finaltesting and adjustment.

If the noise amplitude is too large, hold the commonclamp in one hand and the ± clamps in the other hand.Then, adjust CMR2 and CMR1 for the smallest noisesignal.

Using rubbing alcohol and a folded paper towel, cleanthree electrode areas as shown in Figure 14. Allow theareas to dry. Remove the backing from an adhesiveelectrode and place one on each cleaned area with theelectrode tab (no adhesive) pointing down. Connect theS.E., common lead to the patient’s left shoulder; the blacklead, minus to the right center chest area; and the red lead,plus to the lower left rib area. This electrode configurationis shown in Figure 15.

After a few seconds, the scope should show a pattern.Adjust CMR2 to minimize the noise in the pattern, thenadjust CMR1 to further reduce the noise pattern. Adjustthe GAIN pot so that the heart beat signal (QRS complex)has about a 1V amplitude.

The last adjustment is the heartbeat LED level. Turn theHB pot until the LED lights, then back off the adjustmentto where the LED turns off but flashes each time the QRScomplex is observed (on each heartbeat). It is importantto note that the results are dependent on clean firmly

30 February 2017

■ FIGURE 12. ECG setup for adjustment.

■ FIGURE 14. Nikotab elctrode placement.

■ FIGURE 13. Zietnitz scope setup screen.

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 30

Page 31: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

attached contacts to obtainthe clearest waveforms.

Reading the ECGWaveforms:What doThey Mean?

The waveformsgenerated by the heart whenit is beating can indicate many things. First, the distance(time) between beats indicates the rate the heart is beating.For example, if the time between beats is .75 seconds, theheart rate is 80 beats per minute, BPM, calculated by theformula, BPM = 60/time) = 60/.75 = 80. For .428 seconds,the BPM = 60/.428 = 140 BPM.

Other things like uneven beats (arrhythmias) show up asvaried spacing between beats. This happens very often inolder people (like myself). Inverted “T” waves may indicatepotassium levels that are too low or ischemia (restrictedblood flow) due to arterial plaques or blockages.

Other waveform anomalies can indicate damaged hearttissue, electrolyte imbalances, ectopic firing, atrial orventricle fibrillation, etc. It is left to the reader to consultwith a health care professional or cardiologist if they feelsomething is abnormal.

There are many texts available for understanding andinterpreting ECG waveforms. Here are some for you tocheck out:

• www.practicalclinicalskills.com/ekg.aspx• www.practicalclinicalskills.com/ekg-interpretation.aspx• www.practicalclinicalskills.com/ekg-course-

contents.aspx?courseid=301• www.merckmanuals.com/professional/cardio vascular-

disorders/cardiovascular-tests-and-procedures/electrocardiography-ecg

• https://tmedweb.tulane.edu/portal/files/open-access/clinical-diagnosis/ekg_reference_sheets.pdf

Conclusion and FinalThoughts

The unit worked beautifully when I tested it on myself,my wife, and friends. The tracings were clear and detailed.Some of the recordings I captured and saved are shown inFigures 17 and 18.

I have included the actual trace recordings which can bedownloaded from the article link. If readers have anyquestions, you may contact me at [email protected]. NV

February 2017 31

■ FIGURE 17. My ECG waveform.

■ FIGURE 18. My wife’s ECG waveform.

■ FIGURE 15. Lead IIdiagram.

■ FIGURE 16.Einthoven diagram.

Hoffman - EKG project - Feb 17_Blank Project NV.qxd 12/30/2016 3:08 PM Page 31

Page 32: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

32 February 2017

BUILD IT YOURSELF

About a year after I haddesigned the RF generator(N&V June 2014), I startedto toy with the idea ofadding a sweep function toit. A couple of months later,I completed the design andprototype of this adapterthat has relatively simplecircuitry with a non-criticallayout; it’s quite economicalto build; and draws itspower through a short cablethat plugs into a connectorat the rear of the RFgenerator. This is a five-conductor cable thatconsists of three powerleads and two interfaceleads. This combination iseasy to use and hasadequate performance.Although it is focused foruse on my original generatordesign, the basicarchitecture can bemodified for use withcommercial RF generatorsthat are based on varactordiode tuning.

Add Sweep Function to Your

RF SIGNALGENERATOR

By Robert Reed

There were many of these units manufactured during the ‘70s and ‘80s,and one may be sitting on your test bench now. One shortcoming isthat my RF generator design has no overlapping RF bands such as my

sweep generator has (N&V December 2013). This may not pose too much ofan inconvenience and will be touched on later in this article. Again, the mainbody of this article will be directed towards my design but with occasionalside notes pertaining to commercial equipment.

Theory of OperationThe basic architecture of this adapter generates a ramp for driving the

generator’s varactor diode and also a synchronized ramp wave driving thescope’s horizontal axis. Features are Auto (ramp) or Manual tuning, SetSweep Start and Stop Frequency, Variable Sweep Rate, and various alertlamps, plus an overload alarm (over-driving varactor).

Referring to Figure 1, the sweep ramp is formed by Q1, Q2, IC1a, andassociated components. Q2 is configured as a constant current generator;this current level is controlled by a fixed R6, R7 bias voltage on its base andthe resistance of R8, R9 (in SLO position) and the 5K Sweep Ratepotentiometer (pot) connected to its emitter. Varying the emitter resistanceproduces a change in the collector current which charges C2 in a very linearfashion and at a rate set by that emitter resistance value.

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 32

Page 33: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Obviously, this charging would just continue up to thesupply voltage (+12V) and then sit there forever withoutsome sort of reset incorporated. This is the function ofcomparator IC1a: to trigger at some arbitrary level (in thiscase, approximately 8 VDC) turning Q1 on hard anddischarging C2. The C2 voltage drop immediately resetsthe comparator and then the whole process starts overagain, thus producing a train of ramps at a rate set by theQ2 emitter resistance chosen. C1, R2 add some stabilityand hold time for completely discharging C2.

In this design, the sweep rate is approximately 10-100Hz, and in SLO Sweep about 15 seconds per sweep.When S1a is switched to the manual position, the ManualSweep pot produces a dot on the scope’s X axis thatmoves from zero to the full 10 major graticules on thescreen. This will indicate the exact frequency at anyposition on the display, and comes in handy for closerexamination and spot checking along that axis.

The ramp voltage or the DC voltage developed acrossC2 is buffered by IC1b, and further buffered by IC2bbefore entering the outside world through a BNC jack onthe rear of the adapter unit to the oscilloscope X axis. The100Ω resistor R11 is for stabilizing the op-amp under mostany reactive load conditions it might encounter. You willsee these stabilizing resistors in other outputs, so nofurther explanation of them is necessary.

The IC1b op-amp also feeds two other nodes: thedischarge comparator at R1 and a calibrated attenuator S4which is the Sweep Width Control. Just prior to S4, switchS3a is called out as the Set Sweep switch.

In the run position,the ramp voltage isadjusted by the 2K caltrimmer to a voltage peakthat exactly equals therequired varactor tuningvoltage (Vt) span. In theset position, a DC voltageis set to match thatvoltage by adjusting the5K cal trimmer. Alsoduring final calibration, theManual sweep pot will becalibrated with its 2K caltrimmer to match the DCvoltage of the S3a Setposition.

The Sweep Widthswitch, S4 is the coarseadjustment for setting thefrequency span of thedesired sweep. The 10KVernier pot is the finecontrol used inconjunction with S4. This

pot is buffered from S4 by IC1c for two reasons: First, Ihad one oddball op-amp left over from the initial design;and second, this was a good place to incorporate it as Idon’t want the pot or anything else changing the load onS4. Remember R15, R16, R17 are part of the calibrationstring. I want to keep their values isolated from anyadditional or changing loads. IC2a is wired as a bufferwhich insures very low impedance on this lead, and sendsthe Vt ramp voltage to the RF generator.

IC1d is a comparator that monitors the total Vtvoltage applied to the RF generator varactor. This monitorsthe Vt output stage in the generator. Its trip point is set tothe maximum voltage that the varactor was designed tohandle. That voltage may be pure DC, Ramp AC peak, orthe combination of both. Its purpose is to alert the userthat an illegal operation has occurred and requires somereduction of the Vt voltage. This warning indicator is theonly way you will know if the Vt is set too high and isbeing over-driven, resulting in a flat spot near the end ofits sweep action.

The tripped comparator turns on Q3 hard, and drivesthe alert LED. C3 is incorporated to give some hold to thatturn on time so as to allow the LED to stay on longenough to view it when the comparator is just starting tosee the very peak of any ramp voltage that is present. S1band S3b are the other halves of these DPDT switches andare used to turn on small LEDs to alert the operator totheir status. Strictly optional, but in the original design,there were several occasions of running sweep testingwhere I did not realize switches were not in their final

February 2017 33

Post comments on this article and find any associated files and/or downloads at www.nutsvolts.com/magazine/article/February2017_Add-Sweep-Function-to-RF-Signal-Generator.

■ FIGURE 1.

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 33

Page 34: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

proper positions to do so. Getting false results from thetest was very confusing and annoying until I realized it wasoperator error. They add virtually no extra cost and addvery little load to the power supply requirements (about 3mA each).

ConstructionReferring to Figures 2 and 3, the completed front and

rear views are shown. The front panel measures 4.5” widex 4.0” high. The circuit board measures approximately 3”square and is a modified RadioShack board (#276-168). Ijust love these boards as they readily accept DIP socketsand have power busses running right underneath them. Asseen in Figure 2, the board just folds over the back side ofthe front panel and is mounted to the front panel centerpost by one 8-32 screw. The depth of this whole assemblyis approximately 2”. I built it this way so as to have easyaccess to the board component side for calibration and/ortroubleshooting, and yet still have easy access to theunderside with only the removal of one screw.

One thing to note in the photo is that the Manualsweep pot and the Vernier pots are shown as single-turnpots. These were ultimately changed to 10-turn pots of thesame value (10 KΩ) for reasons I’ll describe later. I wantedan enclosure as small as possible, but with the controlpanel angled for comfortable operation, so the slope frontstyle immediately came to mind. At that point, I started

cruising the Internet for a metal box that wouldbe suitable, but at a lowest available price of $75,it was out of the question. Since this circuit didnot require metal for shielding protection, I nexttried plastic.

Prices were still too high, and nothing had agood fit for my front panel size. Since I decided Ididn’t need a shielded box and I happen to be awoodworker, wood was my next logical choice.The material I used was some leftover scrapaircraft plywood about 0.15” thick.

I cut out six panel pieces and glued themtogether. Once cured, I finger-smeared a fillet ofBondo auto filler along all the inside corners foradded strength. All in all, though, a rectangularbox would be sufficient — especially with fold-down rear feet that would hold it at the properangle when in use.

As can be from Figures 1, 2, and 3, thelayout is fairly simple and straightforward. Thecable leads to the generator were brought out therear of the adapter box through a grommettedhole. The 14” cable was just laced every coupleof inches and terminated in a seven-pin plug thatlooks similar to an XLR style. A mating jack wasinstalled in the rear panel of the RF generator toaccept this. From there, the jack was wired to theproper locations on the control board as shownin Figure 4. Alternatively, you could just run leads

out of a hole and use an outboard inline connector. Tworesistors will have to be installed in the generator for theVt and sense leads; you should have room left on thecontrol board for these.

Too tight? Just solder one end of them snug to theboard in a vertical position and tack the incoming leads toa short stub on the other end. Tie in the power leadswherever convenient. I did use shielded leads for theVt/sense lines, and tied their shields to ground ONLY atthe adapter unit end. This was probably overkill as all linesexiting the circuit board were designed for lowimpedance; generally less than 100Ω.

The power required to operate the adapter unit is ±12VDC at 15 milliamps. If you built your generator powersupply as originally published, it can handle the addedload. If not, then pre-check it with a suitable resistive loadfor those requirements to make sure it’s up to the task.

After the first prototype was completed and in thetesting stage, it was apparent that the Manual sweep potand Vernier pot needed more resolution than the single-turn pots originally installed. I wanted to replace themwith three-turn pots in these locations. They were hard tofind; only 10-turn pots were commonplace on eBay andquite cheap. I did locate some three-turn pots from a smallwest coast distributor and promptly put my order in forthem. I paid a bit more than I wanted to, but they werethe only ones I could locate.

In the meantime, I wanted to continue my testing, and

34 February 2017

■ FIGURE 3.

■ FIGURE 2.

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 34

Page 35: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

subbed in a pair of 10-turn pots Ihad in stock.

Funny thing is that by the time Ireceived my three-turn pots, I wasdelighted with the way the 10-turnpots performed. I originally thoughtthese would have required toomuch fiddling around to adjustthem. However, they were reallynot that bothersome — especiallywhen you consider that they arebasically for setting up the sweepparameters, and then just get onwith the sweep testing at hand. Theresolution is such that itovershadows any minorinconvenience of their usage.

Needless to say, the 10-turnswon out and the newly acquiredthree-turns were stored away foruse in another project. While weare on the subject of multi-turnpots, I have to mention that about ayear ago I replaced the fine-tuningcontrol on my RF generator with afive-turn pot and it made a world of difference in tuning toan exact frequency — especially on the higher bands. Youmay want to do the same, as it is well worth the effort.

There are a fair amount of wires interconnecting thecircuit board and front panel. I wanted to bundle them,yet easily be able to identify them at the other end bycolor-coding them. Having only seven or eight colors tochoose, I quickly ran out of options. So, I used a trick fromthe past to reuse the same colors by marking them with acontinuous stripe. Clamp one end of the wire in a viceand while drawing the wire tight, trace a line down itslength with a black felt tip pen. A blunt one works thebest and one pass is adequate. Additional passes willremove more ink than they lay down.

Several precision metal film resistors are used in thiscircuit. Their actual ohmic value is not super critical, andnear values may be used as long as they are within a fewpercent of the schematic values. Basically, they are usedfor their tighter temperature stability. Resistors R15, R16,and R17 can be off value somewhat, but the total of theircombined resistance should be close to the design valueof 10K as this is part of the calibration string. Aftercompleting construction, check all controls for operation.If they are in the ball park, you can proceed withcalibration.

Calibration andOperation

The original design of my RF generator calls for a Vt+0.6 VDC to -6.2 VDC which is a span of 6.8 VDC. Dueto component tolerances, this could vary from unit to unit.

For now, let’s assume that they are all identical to establisha standard of calibration and test setup procedure. I onlymention this if your situation is slightly different and thecalibration voltages might have to be changed. I tried tokeep the calibration pot resistance small in relation to theoverall strings of resistors associated with them. This is dueto the fact that they would be the most unstable resistanceof those networks, and I wanted the 1% metal filmresistors to make up the bulk of the load because of theirsuperior stability. So, if you run out of pot travel in thecalibration procedures, you will have to go up or down invalue from the associated resistor of that particular string(i.e., R10, R13, R14, R22).

Begin the calibration procedure by turning the Manualsweep pot and the Vernier fully clockwise; S4 at the 100%position. Place S1a in the Auto position, S3a in the Runposition, and the Sweep Rate at mid position. Scopeprobe IC1b’s output; you should see a very linear ramp ofabout 8V peak. Place the scope probe at the wiper of S4in the 100% position and adjust the 2K cal pot that feedsthis switch for 6.8V peak.

Now, place S3a to the Set position and adjust the 5Kpot feeding that Set position for a DC voltage exactly thesame level as the sawtooth peak (6.8 VDC). Set S3a backto the Run position and S1a to the Manual position.Adjust the 2K cal pot feeding that control for exactly thesame voltage as the previous DC voltage (6.8 VDC).

Now, the Auto sweep level (ramp) and Manual sweeplevel (DC) will always track each other exactly, no matterhow the testing setup is arranged. Of course, the scopetrace and Vt ramp are always in sync by virtue of beinglocked on the circuit board. Leave these controls set as-is

February 2017 35

■ FIGURE 4.

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 35

Page 36: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

for now as they will provide the Vt on the sense lead toperform the next step. To calibrate the over-range LED,you will need the RF generator connected and both itstuning controls fully counter-clockwise. You should seeabout -6.5 VDC at the sense lead input to the adapter.Adjust the 5K cal pot feeding IC1d in a direction to turnoff the LED. Then, slowly rotate in the opposite directionuntil it just starts to turn on. There will be a small amountof hysteresis here which is intended.

This ends the calibration. These pots will never againneed adjusting other than troubleshooting or periodiccalibration checks (every five years?). At this point, I willjust do a “drive-by” on each control from the top to thebottom of the front panel:

ON/OFF: S5 disconnects the Vt out signal output.SWEEP RATE: Varies from 10 to 100 Hz; 15 seconds persweep when S2 is in SLO position.SELECT: Connects ramp to Vt out in Auto position; pureDC to Vt out in Manual position.MANUAL TUNE: Applies DC only to Vt out and moves aspot across the entire scope’s X axis.SWEEP WIDTH: Coarse adjustment of the total frequencyspan desired; % of RF band in use.VERNIER: Provides a fine adjustment of the Sweep Widthsetting.RUN/SET: S3a is used in conjunction with the RFgenerator and is for setting the start and stop frequency ofthe sweep.

The setup for testing requires both instruments to beconnected together and sufficiently warmed up. If yourgenerator does not have an internal frequency counter,one will need to be connected externally. Connect theadapter Scope Output to the horizontal input of yourscope and adjust the scope for exactly 10 full graticules inlength. With the RF generator’s tuning controls at the fullCCW position, switch to the RF band of interest. On theadapter unit, set S1a in AUTO position and S3a in SETposition. Set the Vernier at the minimum (CCW) position.Select the S4 SWEEP WIDTH control for the approximatespan of the RF band selected. For example, if you wereusing the 5-12 MHz range and were only interested in a 2MHz portion of that band, you would place this on 30%giving you a 2.1 MHz maximum span (12-5 x 0.3 = 2.1).These % settings apply to any portion of that bandwhether it is upper, lower, or middle.

Adjust the RF generator’s tuning controls for thedesired start frequency and then adjust the adapter’sVERNIER control for the desired stop frequency. Reset S3ato the RUN position. Connect the RF generator to theinput of the DUT (device under test) and the output of theDUT to the scope’s vertical input and begin testing.Obviously, since the scope trace data isn’t labeled up likea full blown spectrum analyzer, you will have to be doingsome simple math in your head during any testing. If youwork in units of ‘10s,’ it’s really a no-brainer.

Let’s apply this to the above setup. We want toexamine a narrow band pass filter with a moderate “Q” inthe 11 MHz range. We have adjusted the SWEEP WIDTHCONTROL for 30% of any given portion of the 5-12 MHzband. We would like a center trace frequency of 11 MHzand probably a sweep width of 100 kHz per graticuledivision, giving us a total span of 1 MHz which will requirea 10.5 MHz to 11.5 MHz actual span. The start frequencyof 10.5 MHz will be adjusted with the RF generatorcontrols, and then the stop frequency of 11.5 MHz will beadjusted with the adapter’s VERNIER control. In an idealworld, the center graticule frequency would be exactly11.0 MHz with this setup, but in reality — due to inherentnon-linearity in the varactor — it may be off the mark. Thismay be of no concern in wide bandwidth filters, but ismore important in narrower filters. This is where switchingS1a to Manual sweep control comes into play.

Now, we can move a dot across the screen and landat any point on the trace. Since it tracks the rampprecisely, we can read the frequency that the Auto modereads whenever its ramp would cross that given dotlocation. In my experience, if the dot planted on the exactmidpoint of the trace and the desired center frequencywas in error, the scope trace could be shifted slightly tocenter everything up. Rarely would it require more than afraction of a division, and a slight shift would not affectthe test nor lose but a small fraction of the total trace dueto a very small part of it being shifted off screen. However,the wider the band pass of a given DUT, the lessimportant exacting frequencies become.

Back to our test. Our display shows a flat topped passsignal with a 3 dB reduction on graticule lines 4 and 6.Now we know that our filter has a band pass of 200 kHz(two full graticules at 100 kHz per division) with a “Q” of55 as per the common formula of center frequencydivided by the band pass of the 3 dB corner frequencies.What the sweep trace will really show is the symmetryand steepness of the skirts (how fast the filter builds ordrops off the pass frequencies), plus any other spikes oraberration. If all this setup sounds confusing, believe me itis not near as bad as shown. After an hour or so of playingaround with the finished unit (even without a DUT), theoperation will become almost intuitive. To clear the air alittle more, I have taken scope pictures of a few tests Ihave run along with the actual setup.

Figure 5 is a display showing the final tuning of myhigh fidelity AM radio’s 455 kHz IF strip. These filters arestagger-tuned to broaden out the pass band and enhancethe fidelity of the detector stage. The setup was: 455 kHzcenter frequency; 415 kHz start frequency; 495 kHz stopfrequency; with a total span of 80 kHz at 8 kHz per scopegraticule, and showing a 10 kHz band pass at the -3 dBcorner frequencies.

Figure 6 is a sweep of a band rejection filter that Iwanted to verify its location and performance: 19 MHzcenter frequency; 12.5 MHz start frequency; 26.5 MHzstop frequency: Total span 14 MHz at 1.4 MHz per major

36 February 2017

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 36

Page 37: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

scope trace graticule. The filter has a bandreject at 19 .1 MHz and a notch depth of28 dB with a Q of 4.3.

Figure 7 is a sweep of a 100 MHzwideband amplifier I recently completed:110 MHz center frequency; 60 MHz startfrequency; 160 MHz stop frequency; with atotal span of 100 MHz at 10 MHz permajor scope graticule. It just starts to roll offat 108 MHz. Considering I needed to knowthe performance here from “DC” to wellbeyond 100 MHz, I had to begin with thelowest RF band and just spin the RF bandswitch right on through to the last position.All were run at 100% sweep, and due to theexcellent leveling of the RF output, thisdisplayed a reliable presentation from bandto band. When checking any wide bandresponse of a DUT, use this method. Alllower bands here displayed a flat response.

Figure 8 is the same setup as in Figure7, only this time with a detector probe (asshown back in Figure 4) attached to the output. I builttwo of these probes: One is constructed in a very smallmetal enclosure with BNC connectors on each end andthe input terminated into a 50Ω impedance. The otherwas built inside a felt tip marker housing with shieldedleads and terminated with a BNC connector. Although youdefinitely want a Schottky type diode here, afterexperimenting with several, the BAT62 was the winner.This gives fairly linear performance down to 0 DBM levels(about 600 mv p-p), and then enters its square law regionwhere response starts to drop off rapidly.

Some Words on SweepLinearity

To begin, sweep testing is not an exacting science. Inan ideal world, as the scope’s horizontal display istraveling along its 10 major divisions of length, thecorresponding generator frequency would be in an exactstep to those divisions in regards to linearity. This wouldrequire that all “major players” in all these devices wereperfectly linear. Any scope manufactured in the last 40years probably has a near perfect ramp driving its sweeptrace. The adapter’s Vt ramp is perfectly linear. Nowcomes the weak link in the chain: the varactor diode.

Varactors do not have good linearity as far as theircapacitance value vs. the applied bias voltage (Vt). Theyall tend to have a sag or bulge somewhere in their rangeof Vt. There are different methods to partially compensatefor these errors in the Vt driving circuits, but none of themcan completely correct this shortcoming. There are othermethods to correct this by using servo control thatanalyzes the non-linearity through a separate and parallelcircuit path, establishes an error signal, and feeds it backto correction amplifiers in the basic Vt circuitry. Although

this method has superior performance, it is very complexand expensive to build. Any further discussion of thissubject is beyond the scope of this article, and beyond thedegree of accuracy intended for a service gradeinstrument. The best I could do on this design was tostretch out the tuning bandwidth as far as possible, andstill maintain a respectable linearity for that givenbandwidth. Like most design work, it involves trade-offs.

After deciding on the optimum tuning range, I ran aseries of linearity tests. There are different ways to do this.I chose to measure the frequency at each major scopegraticule division (10 in all) as the sweep trace crossedthem. I then computed the frequency error in percentageas to what it should be in a perfectly linear sweep.

I ran tests on each band at the 10%, 30%, and 100%sweep widths, with center trace frequencies alwaysreferenced to the center frequency of that particular band.I made measurements at each graticule division for thesweep widths just mentioned on each frequency band —240 test points in all. I then averaged these for an overallspecification. Here are my results:

100% Sweep (of total band): 1.2% average error and2.4% maximum error.30% Sweep (of total band): 0.2% average error and 0.4%maximum error.10% Sweep (of total band): 0.02% average error and0.05% maximum error.

As can be seen from this data, the narrower thesweep span, the greater the accuracy. Recall that wherethe best accuracy is required is in narrow band sweeping;wide band sweeping is not so critical — especially thefarther we move away from the center frequency. Due toscreen parallax and the thickness of the scope trace, it is

February 2017 37

■ FIGURE 6.

■ FIGURE 7. ■ FIGURE 8.

■ FIGURE 5.

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 37

Page 38: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

unlikely that one could discern a readout much beyond0.5% (1/4 minor division). For that reason, the errors ofthe 10% and 30% bands can almost be dismissed.

For examining DUTs which have very widebandwidths, the setup would be 100% sweep; simply startat an RF band lower than necessary and run through theRF bands beyond what is needed, pausing at variousresponses in the slopes and expanding for closerexamination. The RF generator has excellent flatness ofoutput level, so band hopping will not affect the test. All inall, these specs are satisfactory for most of the tests youmight run.

ConclusionThis sweep adapter was a nice fit for my RF generator

design. For readers that have commercial generators,some changes are likely required. The basic circuitarchitecture will remain the same but modifications willhave to be made for it to work correctly. You first have todetermine the varactor’s tuning range (Vt), which is usuallyabout one octave of frequency. To do this, you will haveto measure the Vt span applied to the varactor byconnecting a DMM directly to the varactor bias resistorON THE INPUT FEED SIDE as shown in Figure 4.Ultimately, this may be the tie-in point from the adapter’sVt output lead.

The feed resistor will usually be in the 5-100K range.Tune the generator through its full travel and make note ofthe voltage and span read. Due to the wide range ofdesigns from different manufacturers, these bias voltagescan be all over the map. They may be anywhere from fivevolts to 30 volts, and in a positive or negative direction, oreven bi-polar. Once you have established the starting

voltage and span, theadapter Vt out lead hasto present that voltage toyour particular generator.

Modifications couldbe as simple as an addedop-amp here to scale,offset, and/or invert thevoltage that the adaptercurrently outputs. Abetter way (if your skillsare sufficient) would beto change gains,polarities, and inversionsin the unit itself, therebynot having to add morestages. The maximum Vtspans that can beobtained with theadapter’s power supplyare from -10.5 volts to+10.5 volts. Beyond that,you will need a separate

higher voltage power supply which would only be used inthe Vt output stage.

One word of caution here is that the Vt feed pointmust be carefully chosen due to unwanted voltagedivision of the internal and external Vts. It’s better if youcan locate a tie-in point farther upstream from the varactor— especially a summing amp because there is nointeraction of inputs at their summing point. This is notrocket science, but if undertaken, you should have acertain knowledge and confidence of what is requiredhere. It goes without saying, a good factory servicemanual or at least a schematic diagram is needed.

Before ending this article, I will again present a quickrundown for the sweep setup:

• Sufficient warm-up time for both units.• Generator-RF band of interest.• Adapter — S5 Sweep on; S1a in Auto position; Verniercontrol fully CCW.• Generator — Set RF tuning controls for start frequency.• Adapter — S3a in Set position; switch S4 for desiredspan; advance Vernier CW to stop frequency.• Place S3a in Run position. Start testing.

Note: Manual tuning may be switched in or out at anygiven time for spot checking an exact frequency at anypoint along the scope X axis trace. This will not interferewith the setup already in place.

So, that’s it. I hope I have not left anything uncoveredhere, but as I have done in previous articles, I’ve includedmy email address for any problems that might arise:[email protected]. Also, I will have additional information inpacket form including artwork, etc., available directly fromme and also at the article link. NV

38 February 2017

PART DESCRIPTION PART DESCRIPTIONR1 22K* C1 1,000 pF MLCR2 1.0 M* C2 1.0 mfd (Do not use ceramic or

electrolytic)R3 20.5K* C3 22 mfd electrolyticR4 39.2K* C4, C6 0.1 μfR5 2K C5, C7 10 μfR6 1.82K*R7 20K D1, D2 1N916 or equivR8 510Ω Q1 2N4401R9 1.5M* Q2, Q3 2N3906R10 5.9K*R11 100Ω IC1 TLO84R12 3.3K IC2 TLO82R13 1.21K* Optional detector diode BAT62-02R14 5.9K*R15 6.98K* S1, S3 DPDT min toggle switchR16 2K* S2 SPST (part of Sweep Rate pot)R17 1.02K* S4 SP three-position wafer switchR18 3.3K S5 SP min toggle switchR19 100ΩR20 2K Sweep Rate pot 5K linear w/swR21 12K Manual Sweep pot 10K/10TR22 8.2K* Sweep Vernier pot 10K/10TR23 12K* Manual Calibration 2K trimpotR24 5.1M Ramp Calibration 2K trimpotR25 51K DC Set Calibration 5K trimpot

Over-Range Calibration 5K trimpot

SWEEPADAPTER

PARTSLIST

Note: All resistors1/4 watt @ 5%* 1% resistors

Reed - Add Sweep to Generator - Feb 17_Blank Project NV.qxd 12/30/2016 3:14 PM Page 38

Page 39: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Because an MCP2515 operates outside anMCU, it can take less time to set up and usethan some MCU’s built-in CAN controllers. Thecontrol registers, message buffers, and flags

prove easy to understand, and C-code clarity improves.The MCP2515 18-pin DIP makes it simple to breadboardand test a circuit, or you can use an MCP2515 module,shield, or cape. Before you start to experiment with anMCP2515 IC, download and print its datasheet (pages 1through 68) which provides complete register descriptions,diagrams, flow charts, and tables (see References).

An MCP2515 relies on Serial-Peripheral Interface (SPI)signals, so almost any MCU meets theinterface requirements. The examplesin this article use an mbed board withan NXP LPC1786 (ARM Cortex-M3)MCU that includes an SPI port. Inaddition to the three SPI signals(MOSI, MISO, and CLOCK), anMCP2515 needs a logic 0 chip selectsignal (/CS) along with power andground. The internal bit rate clockrequires an external crystal.

MCP2515 Architecture

An MCP2515 CAN-controller ICcomprises three transmitter buffers(TXB0, TXB1, and TXB2) and tworeceiver buffers (RXB0 and RXB1)which are shown in Figure 1. Receiverbuffer 0 includes one acceptance

mask (RXM0) and two acceptance filters (RXF0 and RXF1).Receiver buffer 1 includes one acceptance mask (RXM1)and four acceptance filters (RXF2 through RXF5). Thesemasks and filters let you direct CAN messages to aspecific buffer where the MCU can read it. You might useRXB0 for messages with a high priority address and RXB1for other messages within an address range.

The three transmit buffers differ only by name. Eachcan hold as many as eight bytes of data, and each hasassociated control and status bits, as well as an interrupt.The receiver and transmitter buffers have the sameorganization (Figure 2) that comprises a control byte, two

In the first part of this series, you learned about the physical Controller AreaNetwork (CAN) bus, bus arbitration, device addresses, and address masks

and filters. Not all MCUs include a CAN controller and even those that do

can challenge experienced designers. In either case, an external Microchip

MCP2515 CAN controller IC can do the job, and you'll learn how to use it.

Take a CAN Busfor a SpinBy Jon Titus KZ1G

Post comments on this article and find any associated files and/ordownloads at www.nutsvolts.com/magazine/article/February2017_CAN-Bus-Add-Controller-to-MCU.

February 2017 39

Add a CAN

controller to an

MCU that lacks one.

Part 2

FIGURE 1. Each receiver buffer (RXB0 and RXB1) hasits own set of masks and filters. Each transmitter bufferhas registers for an 11- or 29-bit ID, a byte count, andas many as eight data bytes. For clarity, this diagramdoes not include all CAN-controller circuits. (The 29-bitaddress mode goes beyond the scope of this article.)

Titus - CAN bus 2 of 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:18 PM Page 39

Page 40: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

40 February 2017

bytes for an 11-bit address, two bytes for an extendedaddress (18 additional bits), a byte that stores the numberof data bytes in a message, and those data bytes. (Howcan you put an 18-bit address in two bytes?

The SIDL registers hold the two “extra” address bits,

EID17 and EID16.)In the MCP2515 datasheet, Table 11-1 shows

what looks like a CANSTAT and a CANCTRL registerfor each buffer. Not so. An MCP2515 has only tworegisters that affect the CAN-controller and governoperating modes, provide buffer-interrupt signals,and set clock parameters. The datasheet calls allthese bytes “registers,” so I’ll use that term fromnow on. An MCP2515 includes other registers thatcontrol flag bits and CAN bus bit rates.

Application software may identify a register byits address and then read from it or write to it.Register addresses run in sequence from 0x00 to0x7F, but you needn’t try to memorize TXB0CTRL =0x30, RXB1D0 = 0x76, and so on. Two C/C++ files— MCP2515JT.h and MCP2515JT.cpp — defineregister names and their addresses, which simplifyprogramming and make code easier to understand.

An MCP2515 CAN-controller operates in oneof five modes: Normal, Loopback, Configuration,Sleep, and Listen, as set by software. The Normalmode needs little explanation; it lets the IC operateas a device on a CAN bus (with a driver IC, of

course). The Loopback mode “disconnects” the TXCANand RXCAN signals from a bus driver and internallyconnects them. This mode lets people test the transmitterand receiver without disturbing other devices on a bus.This mode does not let you view the TXCAN signal with a

scope or logic analyzer,however. (The Sleep andListen modes go beyondthis article’s scope.)

The Configurationmode provides the onlyway to change thecommunication bit rate,load the filter and maskregisters, and preset severalI/O pins. The MCP2515enters this mode when itreceives power, when itdetects an external /RESETsignal (logic 0), or when itreceives a Reset command(0xC0). This commandwould come from an MCUvia its SPI connection.

SPI TransfersSimplify Software

Although an MCP2515contains 114 registers, theSPI port needs only ninecommands to read andwrite data, modify aspecific bit, cause a reset,

TABLE 1. SPI Instruction Set for MCP2515

Instruction Name Instruction Description

RESET 0xC0: Reset registers to default settings, enter Configuration mode.

READ 0x03: Read a register’s content as a byte.

Read RX Buffer

0x90: Read receiver buffer 0 ID.0x92: Read receiver buffer 0 Data.0x94: Read receiver buffer 1 ID.0x96: Read receiver buffer 1 Data.

WRITE 0x02: Write a byte to a register.

Load TX Buffer

0x40: Load transmitter buffer 0 ID.0x41: Load transmitter buffer 0 Data.0x42: Load transmitter buffer 1 ID.0x43: Load transmitter buffer 1 Data.0x44: Load transmitter buffer 2 ID.0x45: Load transmitter buffer 2 Data.

READ STATUS

0xA0: Read the following bits as one byte:D0: Receive-Buffer-0-Full Interrupt FlagD1: Receive-Buffer-1-Full Interrupt FlagD2: Buffer 0, Message-Transmit-Request bitD3: Transmit Buffer-0-Empty Interrupt Flag bitD4: Buffer 1, Message-Transmit-Request bitD5: Transmit Buffer-1-Empty Interrupt Flag bitD6: Buffer 2, Message-Transmit-Request bitD7: Transmit Buffer-2-Empty Interrupt Flag bit

RX STATUS 0xB0: Read bits to indicate a filter match and message type.

BIT MODIFY0x05: Set or clear individual bits in a register. (Does not apply to allregisters.)

Request to send amessage fromtransmit buffer

0x81: Request to transmit message in buffer 0.0x82: Request to transmit message in buffer 1.0x84: Request to transmit message in buffer 2.

FIGURE 2. Register arrangement for receiver buffer RXB0 andtransmitter buffer TXB0. Other buffers have the same registerarrangement. Software may address these registers individually orsequentially.

Titus - CAN bus 2 of 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:18 PM Page 40

Page 41: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

and report status information. Table 1summarizes the commands and theiractions. Also refer to Table 12-1 in theMCP2515 datasheet.

All MCP2515 communications requireonly SPI write statements that take the formof spi.write(hex_value). The write operationin your MCU’s SPI library might have adifferent format. If so, open theMCP2515JT.cpp file and use search-and-replace operations to substitute yourMCU’s SPI write instruction for spi.write.

Given the nine command types andhex values in Table 1, my MCU resets anMCP2515 with the command 0xC0 sentthis way:

spi.write(0xC0);

You can use a command or register name to makecode easier to understand. The file MCP2515JT.h containsall register definitions such as:

#define RESET_REG 0xC0

and this definition lets you write a code statement:

spi.write(RESET_REG);

The MCP2515JT.h file also provides prototypes forMCP2515 control functions such as: send_0, load_0,readDATA_0, and readRegister. SPI commands andoperations will become clearer as you review a codeexample shown later.

Set Up an MCP2515 Circuit

I created a test circuit (Figure 3) that connects anMCP2515 to an mbed MCU board. SPI pin numbersdepend on the MCU you’ll use, but SPI ports usually workthe same way. The MCP2515 uses SPI mode 0,0 or 1,1and transmits the most-significant bit (MSB) first for eachbyte, or register. My circuit used a 10 MHz crystal,although some commercial modules include an 8 or 16MHz crystal. The crystal frequency and calculated timingvalues govern the CAN bus bit rate.

The MCP2515JT.cpp software includes places for threebit-timing values — CNF1, CNF2, and CNF3 — in thebaudConfig function for standard CAN bit rates. You mustcalculate bit-timing values based on your crystal’sfrequency and the bit rates you plan to use. Then, insertthe calculated values in the MCP2515JT.cpp file to replacethe 0x00 “placeholders.” I calculated values for 125,000bits/sec and used them as shown in the following:

//Set CAN timing constants for 125,000 bits/seccase 125:

//Jon’s values for 10.00 MHz XTAL

CNF1 = 0x01;//Value for MCP2515 CNF1 registerCNF2 = 0xBA;//Value for MCP2515 CNF2 registerCNF3 = 0x07;//Value for MCP2515 CNF3 registerbreak;

I used 125 kbits/sec for tests, and didn’t need anyother timing values. Always document code changes,timing values, and crystal frequency!

Two online calculators give you bit rate timing valuesfor almost any crystal frequency (see References). I ran theSeeed Studio bit-timing software to calculate timingconstants that worked well. You can download theWindows CAN timing software from the Seeed Studiowebsite at www.seeedstudio.com/wiki/CAN-BUS_Shield_V1.2#Set_Baud_Reate. Yes, it’s “reate,” andthe GUI uses Chinese characters, but you’ll see labels inEnglish for the important controls.

Transmit a CAN Message

Before you create an application program, ensureyour MCU’s SPI port operates properly and ensure youhave changed — if necessary — the spi.write statements toconform to the SPI functions for your MCU. I often writetest programs within a simple LED flash loop that runscontinuously. The flashing LED indicates code in the loop

February 2017 41

References

Microchip MCP2515 datasheet, DS21801G:

www1.microchip.com/downloads/en/DeviceDoc/21801e.pdf

For Serial Peripheral Interface (SPI) information, visit:

https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus

For CAN timing calculations, visit:

www.seeedstudio.com/wiki/CAN-BUS_Shield_V1.2

For an online CAN timing calculator, visit:

intrepidcs.com/support/mbtime.htm

FIGURE 3. Schematic diagram for MCP2515 connections with an mbedNXP1786 MCU. My circuit used 3.3V power from the mbed board, but an

MCP2515 will operate with a VDD between 2.7 and 5.5 volts. This circuit doesnot connect to a CAN bus driver IC.

Titus - CAN bus 2 of 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:18 PM Page 41

Page 42: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

42 February 2017

operates, although it might not do what I expect. I tookthis route for MCP2515 tests. You must have theMCP2515JT.cpp and MCP2515JT.h files in your “working”directory, along with any other files the MCU’s compilerneeds; perhaps spi.h or stdio.h. The following stepsdescribe operations used to configure an MCP2515, loada three-byte message, and send it:

1. Define an array (data[8]) to contain data bytes.Preset the first three byte values as you wish.

2. Reset the MCP2515.3. Put the MCP2515 in the Configuration mode.4. Set the baud rate at 125 kbits/sec with timing

constants calculated for your MCP2515’s crystalfrequency, and inserted by you in theMCP2515JT.cpp file.

5. Return the MCP2515 to its Normal mode.6. Use the load_ff_0(3, 0x123, data) function to create

a three-byte CAN message with the identifier 0x123and to put it all in transmitter buffer 0. The threebytes come from the data array defined earlier. Ifind it easier to load all transmitter registers withone function rather than with a separate functionfor each register.

7. Use the send_0() function to have transmitter buffer0 send a CAN frame.

8. Finally, a readStatus() operation lets me see activity— if any — on the MCP2515 serial-out (SO) pin. (Iuse a Saleae Logic brand logic analyzer to capturedigital signals.)

Here’s the demonstration code that is also available atthe article link. The download package includes theMCP2515JT.h and MCP2515JT.cpp files and threecommented demonstrations:

//Program CANJT1.cpp See also file MCP2515JT.cpp#include “mbed.h”#include “MCP2515JT.h”

DigitalOut myled(LED1);//define an LED output

char XXX;//a do-nothing variable

byte data[8] = {0x00, 0x99, 0xF9}; //Array data, 3 bytes

int main(){

reset(); //Reset MCP2515setMode(CONFIGURATION);

//Put MCP2515 into CONFIGURATION modebaudConfig(125);

//Set CAN-bus bit rate to 125

//kbits/secsetMode(NORMAL);

//Back to Normal mode

while(1)//While loop runs forever

{myled = 1;

//LED-blink to show program runswait(0.1);myled = 0;wait(0.1);

//Load 3 bytes of data into Transmit buffer 0, //load address 0x123, & point to data[x] array.

load_ff_0(3, 0x123, data); send_0(); //Transmit the buffer-0 info via CAN-TX //pin XXX = readStatus(); //Read the status bits.

} //End of while loop

} //end of main

Figure 4 shows the TXCAN output signal to which theCAN controller appended a cyclic-redundancy-check(CRC) value 0x0F0F. When expanded, the small “bubble”at the right end of the trace shows a “NAK,” or no-acknowledgment bit.

I had no other CAN device on the bus, so myMCP2515 did not receive an acknowledgment response,which it expected. Even so, the diagram shows the buffertransmission.

Read a CAN Message

You might think a jumper between the TXCAN andRXCAN pins would let communications occur from theMCP2515 transmitter to the receiver. Not so. We have nobus and thus no other “transmitters” that would generatean acknowledgment bit. Thus, the MCP2515 receiverdetects no proper acknowledgment and rejects the entireCAN frame, so we cannot use a jumper to test the CANreceiver. Instead, we put the MCP2515 in the Loopbackmode. As mentioned earlier, the internal loopbackconnection does not affect any external circuits.

In Loopback mode, a receiver buffer should holdinformation sent from a transmitter buffer. Then, we canexamine the receiver buffer and view the 11-bit ID, thebyte count, and the data bytes sent by a test program.Before we can look at the register contents, our softwareneeds two new statements that modify control-register bitsbut leave other bits unchanged.

So, how do we do that? Thefunction bitModify in theMCP2515JT.cpp file does the job.It has the following format andrequires byte sized arguments:

bitModify(register, mask,data);

FIGURE 4. A trace of the TXCAN signal for the simple program shown earlier. My logicanalyzer's CAN decoder option makes it easy to see the data as hex values. Three arrowsmark "stuff" bits all CAN controllers introduce under special circumstances to synchronizetiming between CAN devices.

Titus - CAN bus 2 of 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:18 PM Page 42

Page 43: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

During test runs, I wantedreceiver buffer 0 to accept allmessages, regardless of their 11-bit ID. The RXB0CTRL registerincludes two bits — RXM1 (D6)and RXM0 (D5) — that governthe acceptance masks andfilters for that buffer. To disablethe filters and masks, I must setonly these two bits to 1. Theother six control bits mustremain unchanged. In this case,I used mask byte 011000002 toidentify the two bits to change,and the data byte 011000002 torepresent what I wanted thosetwo bits to change to:

bitModify(RXB0CTRL, 0x60,0x60);

Figure 5 shows theRXB0CTRL register contentsbefore my program used the bitModifyfunction. The mask byte indicateswhich bits the data byte may change,and the data byte of 011000002 causesthe RXM1 and RXM0 bits to contain 1s.Caution: Don’t confuse bit-wise masksused with bitModify operations withthe acceptance masks used to set ID-filter characteristics (see Figure 1).

I need one more bitModifyfunction in the test program. When abuffer receives a valid frame, it“notifies” the MCU via a flag bit in theCANINTF (CAN interrupt flag) register.A 1 indicates “data ready,” and a 0 indicates “no newdata.” Software can read this register regularly and test theRX0IF (D0) bit associated with receiver-buffer 0 or theRX1IF (D1) bit for receiver-buffer 1.

When a flag bit indicates new data has arrived,software can read it and clear the RXnIF bit. According tothe MCP2515 datasheet:

“This bit [RX0IF or RX1IF] must be cleared by the MCUin order to allow a new message to be received into thebuffer. This bit provides a positive lockout to ensure that theMCU has finished with the message before the MCP2515attempts to load a new message into the receive buffer.”

So, our test program must clear the RX0IF and RX1IFbits to logic 0s before we transmit a new frame to one ofthe receivers. Another bitModify statement handles this task:

bitModify(MCP2515INTF, 0x03, 0x00);

I added two new functions — readSID0_asHex() and

readSID1_asHex() — to readreceiver-buffer standard 11-bitaddresses and convert them toa single hexadecimal value. TheCANJT2.cpp program in thedownload package illustratesthe address-read and address-display code.

SPI Register Access

The CANJT2.cpp programreads the RXB0SIDH andRXB0SIDL registers and displaysthe equivalent hex ID in aterminal window. I used theParallax Serial Terminal (PST)and TeraTerm software at 9600bits/sec (8N1) to receive datafrom the mbed MCU board viaa virtual serial USB port. Theterminal window should display

“RXB0 ID = 0AA” and “RXB1 ID = xxx”again and again, where a hex addressreplace the xs. The RXB0 ID equals“0AA” because it’s the address set inthe code. You may change the addressand run the program again to ensurethe receiver got a message with thenew address.

Figure 6 shows a portion of theSPI signals sent to and from theMCP2515 CAN controller when I ranthe CANJT2.cpp program. The uppertrace shows MOSI activity; that is, datasent to the MCP2515.

The middle trace shows the SPI clock, and the bottomtrace shows the SPI data sent from the MCP2515 to theMCU.

The test program calls the function readSID0_asHex inthe MCP2515JT.cpp file. This function includes thestatement spi.write(READ_RX_BUF_0_ID); which sends0x90 to the MCP2515 (see Table 1). However, thisstatement does not transfer any information to the MCU.You can see the 0x90 instruction in the upper trace andeight clock pulses below it. The 0x90 “tells” the CANcontroller to point to the RXB0SIDH register.

The next two statements in the readSID0_asHexfunction each transmit 0xFF to the MCP2515:

HiAddr = (unsigned short) spi.write(0xFF);LoAddr = (unsigned short) spi.write(0xFF);

Only the MCU acts as the SPI master and only it cangenerate SPI clock pulses. Thus, the MCP2515communicates information to the MCU only when theMCU creates the needed clock signals. In this example,

February 2017 43

FIGURE 5. This example shows how the bitModifyfunction changes the state of only the RXM1 and RXM0bits in the RXB0CTRL register. The mask byte must holda logic 1 for any bit position(s) you want to change. Thedata byte controls the final state of those selected bits.

FIGURE 6. The top trace shows theMCU transmitted 0x90 to the MCP2515,

which causes the CAN controller topoint to the RX0SIDH register.

Titus - CAN bus 2 of 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:18 PM Page 43

Page 44: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

the 0xFFs amount to “do nothing” instructions theMCP2515 ignores. However, the two sets of eight clockpulses from the MCU cause the MCP2515 to send theRXB0SIDH and RXB0SIDL bytes into the MCU. HiAddrstores the RXB0SIDH (0x24) value and LoAddr stores theRXB0SIDL (0x60) value.

The function finally manipulates the bits and returns ahex value to the calling program. Remember, the SIDHand SIDL registers save bits in an “offset” manner.Addresses in filter and mask registers use the same bitformats.

Update Your Address

You might ask, “Okay, the MCP2515 pointed to theSIDH register, so how does it get data from the SIDLregister, too? There’s no command to point to thatregister.” After the MCU points to a register and performsa read or write operation, the CAN-controllerautomatically increments the address to point to the nextsequential register. If you must read bytes from, say, all theRXB0 registers, you don’t need to address eachindividually. Just start with the SIDH register and continue

to send 0xFF do-nothing instructions.Each time you do, the MCP2515 willcontinue to send the MCU all theregister bytes in order: RXB0SIDH,...SIDL, ...EID8, ...EID0, ...DCL, ...D0,and so on. You could create a loopto read all 13 registers and save theirvalues in an array for later use. In theMCP2515JT.cpp file, you will seeseveral such loops. After you retrievedata bytes, use them as you wish.

The MCP2515JT.cpp file includesthe functions setMask_0 andsetMask_1 that set the receivermasks (RXM0 and RXM1). It alsoincludes six new functions(setFilter_0 through setFilter_5) thatlet you put values in mask or filterregisters. These functions take a hexvalue between 0x000 and 0x3FF (0to 2047).

You can experiment with theseregisters to see how they affectreceipt of data with differentaddresses from the transmitter. Note:Software can change filter or maskinformation only when you put theMCP2515 in its Configuration mode.For an example that demonstratesCAN-filter operation, seeCANJT3.cpp and try it. The listingincludes instructions.

Coming Up

In the final article about theMCP2515, you’ll learn about lagsand interrupts, how to interpret bitson the CAN bus, and why otherCAN devices must acknowledgereceipt of messages. NV

44 February 2017

A L L

E L E C T R O N I C Swww.allelectronics.com Order Toll Free 1-800-826-5432

Wi-Fi MODULE, ESP8266MOD

DIRECTIONAL SPEAKER WITH INTEGRATED AMP

$7500each

$535each

A self contained WiFi module

capable of either hosting an

application or offloading all

Wi-Fi networking functions

from another application processor.

Pre-programmed with an AT command set

firmware.

CAT# ESP-12E

Panphonics "Sound

Shower." 24" square,

flat-panel speaker with

an integrated amplifier.

Highly directional sound

pattern provides a targeted

audio signal to a person

standing under it. Designed to fit a drop-

ceiling grid, or suspend from ceiling or wall.

23.6" x 23.6" x 1.64".

CAT# SK-600

SERIAL INTERFACE MODULE FOR 16 X 2 LCDSArduino compatible controller

for 16 x 2 LCD modules.

Also has output for LED

backlight. 16-pin header

solders into LCD. 42 x 19 x 8mm pc board

(excluding header pins).

CAT# LCD-SI$300

each

LED MOTION SENSOR LIGHTTurns on when it senses movement

and turns off after 90 seconds.

3.25" x 2.03" diameter. Uses three

AAA batteries (not included).

CAT# MSL-04 $595each

4-CHANNEL RELAY MODULEUses data signals to

selectively switch four

5V relays, each

capable of handling

10A loads. Onboard

LED indicators light when

a relay is switched. Screw

terminals for relay outputs.

0.1" header for voltage and signal input.

75 x 55 x 18mm.

CAT# RLM-4$1150

each

40 X 60MM SINGLE HOLEBREADBOARD280 point multilayer epoxy

board. Double-sided with

pre-tinned through-holes.

CAT# SB-36 $275each

40 EDUCATIONAL ELECTRONIC PROJECTS,BOOK & PARTS KITHands-on curriculum

of fun and illustrative

electronics projects

that teaches the funda-

mentals of electronics.

STEM Compliant.

Color photos and illustrations. Projects are

designed to be breadboarded, taken apart

and reused. Includes 88 page manual,

solderless breadboard and all the parts

necessary for 40 projects.

CAT# KT-40

$2495ea.

5MM RED-GREEN FLASHING LED180 flashes per minute.

CAT# LED-6F

45¢each

100 for 40¢ each

Yoshito Onishi, Kyle Crockett, andPatrick Cruce created the originalMCP2515 code, which I used andmodified. Thanks, guys, I appreciateyour work.

Titus - CAN bus 2 of 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:19 PM Page 44

Page 45: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

The digital I/O specifications for the MyRIO unit are:inputs are 5V TTL compatible; outputs are 3.3VLVTTL at 4 mA sinking or sourcing. These low voltage

and current levels are not suitable to directly drive muchof anything other than an LED. There are, however, severaldevices available that can boost the outputs of the MyRIOup to any level of AC or DC voltage and current youwould typically want to control in the realworld. There are other devices available thatcan convert about any level of AC or DCvoltages back into a suitable level for theMyRIO to input from. Most of these devicesalso provide protection from high voltage levelsentering back into the MyRIO unit, as well asthe PC that might be connected to it.

On the output side of things, we willexamine two different devices in this article:SSRs (solid-state relays) and EM relays(electromechanical). Photo 1 shows a DC SSRand Photo 2 shows an AC SSR — both of theseare available from www.jameco.com for justunder $10 each. SSRs typically cannot handleboth AC and DC loads because of their finaldriving components. DC SSRs typically use atransistor to drive the loads, and because ofthis they cannot handle the reversing polarityof AC loads. AC SSRs typically use a triac todrive the loads, and rely on the AC signalreversing its polarity and passing through 0V so

that the triac can be turned off when the control signalturns off. In other words, if an AC SSR were to drive a DCload, it would not turn off the load even when thecontrolling signal is turned off; probably not a good idea.

If a DC SSR drove an AC load, it would rectify it orcut half of the AC waveform off. Figure 1 shows thesimplified circuitry that might be found in a typical DC

COMPUTERCONTROL AND

INTERFACING WITHTHE NI MYRIOBy David Ward

February 2017 45

Part 3:ControllingReal World

ElectricalLoads and

Devices.

Post comments on this article and findany associated files and/or downloadsat www.nutsvolts.com/magazine/article/February2017_Computer-Control-with-NI-MyRIO-Control-Electrical-Loads-and-Devices.

PHOTO 2. PHOTO 1.

FIGURE 1.

The previous two installments in this series of five articles aboutthe National Instruments’ (NI) MyRIO have demonstrated how toinput from a built-in pushbutton (BUTTON0) and output to a built-in LED (LED0), and control these wirelessly from an Apple iPad.While this is a good start into computer control, the “real world”outside of the MyRIO unit typically involves I/O to much higherAC and DC voltages and currents than the MyRIO can tolerate.

Ward - MyRIO series Part 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:23 PM Page 45

Page 46: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

46 February 2017

SSR, and Figure 2 shows the simplified circuitry thatmight be found in a typical AC SSR. The protectivepart of both SSRs is the optical isolator shown onthe control or input lines of these devices. All thecontrolling or input side of the circuit basically doesis energize an LED — often an infrared LED toprevent interference from visible light — which, inturn, shines on the base of a photo transistor.Therefore, the only connection between the loadcircuit and the control circuit is a beam of light.

This can protect your controlling circuit fromvoltage levels into the thousands of volts in some SSRs(2,500V on the two SSRs shown in Photos 1 and 2). Ifthere is a problem, the SSR may be destroyed in theprocess, but hopefully no damage will get back into thecontrolling circuit.

In order to control either a DC or AC load with theMyRIO, a change will have to be made to the demo VIwe have been working with in the past two articles. Openup the final demo VI from the second article. On theblock diagram, place a digital output as shown in Figure 3;

Functions > myRIO > Digital Output. When placingthe digital output on the block diagram, anotherwindow will appear as in Figure 4.

A configuration tab and pull-down menu willallow you to see all 40 digital I/O lines available; wejust need the first one at this time: A/DIO0 (pin 11).This will let our VI output to MXP port A DIO 0.Wire the digital output in parallel with the otheroutputs as shown in Figure 3. It’s always a good ideato have your VI shut things off when closing, so copyand paste this icon into the last frame of the VI asshown in Figure 5; ctrl C/ctrl V will work for this.Make sure that the closing frame icon has a constant“F” wired to it so that it will turn off DIO 0 when theVI is closed.

To see if this output will work, you can test it byconnecting the anode of an LED to output DIO 0 inseries with a 220 ohm resistor to ground on the MXP

FIGURE 2.

FIGURE 3.

FIGURE 4.

FIGURE 5.

PHOTO 3.

Ward - MyRIO series Part 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:23 PM Page 46

Page 47: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

expansion board as shown in Photo 3.When you run the VI, you should beable to turn the real world LED on fromeither BUTTON0, the pushbutton on theVI, or from the iPad Data Dashboard. Ifthis works, you are ready to connect aDC SSR and control a load of up to fouramps at up to 30V DC. However, bevery careful any time you attempt to dothis. It would be very easy for a loosewire to come in contact with the MyRIOconnections and damage it.

Let’s demonstrate connecting theKyotto DC SSR to a 12V DC load at thistime. The specifications for the Kyotto KF0604D SSRshown in Photo 1 are: an in or control voltage from 3VDC up to 32V DC at about 2.5 mA at 3.3V DC, and aload voltage of from 3V DC up to 60V DC at up to fouramps. The 4D in the part number stands for four ampsDC. This SSR also protects the control circuit up to2,500V. Figure 1 shows the schematic for the circuitryshown in Photo 4.

For the AC SSR, nothing in your VI would need to bechanged. The specifications for the Kyotto KB20C02A ACSSR shown in Photo 2 are: the inputs are the same as forthe DC SSR, and the load voltage range is from 24 VACup to 280V AC at two amps. The 2A in the part numberstands for two amps AC. This AC SSR can protect theinput up to 2,500V, and it can control AC voltagefrequencies from 47 Hz up to 70 Hz. Figure 6 shows theschematic for connecting this SSR up to 2-120V ACreceptacles.

It would be verydangerous to try andconnect this SSR upto 120V AC withloose wires layingaround. I constructed the control box shown in Photo 5.Inside are two AC SSRs, so that two loads can becontrolled independently; see Photo 6. To control twoloads separately through one receptacle, the ACreceptacle hot side (the narrow slot on the receptacleface) connection tab is broken off. Refer to Photo 7 whichshows the tab before breaking, and Photo 8 which showsafter the tab is broken with needlenose pliers.

Enclosing all of the high voltage connections in aplastic box as shown is much safer than working withloose 120V AC wires which could not only damage theMyRIO and the PC connected to it, but could cause afatal electrocution or start a fire. Great care must be taken

February 2017 47

FIGURE 6.

PHOTO 4.

PHOTO 5.

PHOTO 6.

PHOTO 7. PHOTO 8.

Ward - MyRIO series Part 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:23 PM Page 47

Page 48: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

when enclosing lowvoltage wires andconnections alongwith high voltagewires andconnections in thesame box.

All connectionsare carefullyinsulated with heatshrink tubing andelectrical tape. Besure all highvoltage and lowvoltage wires arephysicallyseparated fromeach other asmuch as possible.

Being cautious cannot be over-emphasized when dealingwith these higher voltages and currents.

Another great device for controlling higher voltageand current AC and DC loads is the EM relay; see Photos9, 10, and 11. This particular relay is available fromwww.jamco.com for about $6 and the relay socket foranother $5. The EM relay can really be broken into twoparts: the coil used to control the relay, and the contactsthat are controlled by that coil. Relay coils are usuallyconstructed to be energized by either DC or AC voltages(usually not both), and can be designed to operate atvoltages such as: 6V, 12V, 24V, and 120V. As you can seein Photo 12, this relay has a 12V DC coil.

This coil has a DC resistance of 156 ohms and wouldtherefore draw 12V / 156 ohms = 77 mA. This, of course,cannot be driven directly by the 3.3V LVTTL 4 mA outputsof the MyRIO unit. Probably the easiest way to solve thisproblem is to drive the coil with a DC SSR. This may seemlike duplication until you look at the contact ratings andconfiguration of the relay; refer to Photos 9 and 10.

This relay’s contacts are configured as a DPDT(double pole double throw; six terminals)switch; probably the most common type ofrelay contact configuration you will find.The SSRs can only operate as SPST (single

FIGURE 7.

PHOTO 9.

PHOTO 10.PHOTO 11.

PHOTO 12.

48 February 2017

Ward - MyRIO series Part 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:23 PM Page 48

Page 49: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

pole single throw; twoterminals) connections.Since the contacts aremechanical connections,they can operate eitheran AC or a DC load.Note the high currentand voltage ratings aswell: 12 amps for up to240V AC 60 Hz loads,and 12 amps for up to30V DC loads.

They are veryreliable, and the contactsare very forgivingwhen overloadedfor brief periodsof time whencompared to thesemi-conductorsused in SSRs.Relays are quitecheap whencompared to SSRsthat can handlethe same currents and voltages. Figure 7 shows how anEM relay might be connected to a 120V AC load andcontrolled with an SSR.

As far as matching real world input voltage levels andtypes to the MyRIO, there are devices called inputmodules which are like SSRs in reverse; see Photos 13and 14. Like SSRs, because of the circuitry inside of them,they are designed to handle either a DC voltage or an ACvoltage, but not both. These items are available fromwww.alliedelec.com for just under $30 each. The yellowAC input module, IAC5, can take from 90V AC up to140V AC and convert it down to a 5V TTLlevel signal. It also uses optical isolation toprevent high voltage levels from getting backinto the output (computer) side of things.

The white module, IDC5, can take from3.3V DC up to 32V DC and convert thatdown to a 5V TTL level signal as well. Figure 8demonstrates how these input modules can beconnected to convert real world voltagesdown to levels that the MyRIO can tolerate.

Please exercise extreme caution whendealing with the high level voltages andcurrents demonstrated in this article. However,if you really want to control something, you willneed to learn how to safely interact with them.

SSRs will need to be used in the finaltemperature control project that will bedemonstrated in the final article of this series;see Photo 15. A 120V AC 60 wattincandescent bulb will be used as a heater and

a 120V AC fan will be used as the cooling device.

The fourth article next month will examine inputtinganalog voltages and converting them into digital numbers:analog-to-digital conversion (ADC), and also convertingdigital numbers back into analog voltage levels (digital-to-analog conversions; DAC). ADC will be needed in thefinal temperature control project to detect the analogtemperature, so decisions can be made as to when to turnthe heater and fan on and off. NV

FIGURE 8.

February 2017 49

PHOTO 13. PHOTO 14.

PHOTO 15.

Ward - MyRIO series Part 3 - Feb 17_Blank Rough NV.qxd 12/30/2016 3:24 PM Page 49

Page 50: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

To tie all of this IoT and sensor stuff together, you willneed some type of compilation system. You can tough

it out with assembler, but you will find very little assemblerprogramming help out there. Although BASIC is holding itsown, C is the dominate IoT programming language as youcan easily find multiple C based compilation systems for

the popular PIC and ARM microcontrollers. A workingknowledge of the C language will also open the IoT doorto other popular platforms such as the Raspberry Pi andBeagleBone.

Some of you are still sitting on the C learning fence.This is your chance to leap to the C side as we are about

to embark on asensor-heavy IoTjourney that will befueled by the CCSPIC C compiler.

The HardwareFirmware isn’t

very useful withoutsome associatedhardware. In ourcase, that hardwareconsists of the CCSE3mini. The E3miniis based on the 20-pin PIC18F14K50.Although the USB-enabled E3mini isequipped with ananalog-to-digitalconverter (ADC), an

THE DESIGN CYCLE

See C More Clearly with the E3mini■ BY FRED EADY

50 February 2017

It’s knowing how to do the little things that allows us to do the big things. Today’s IoT (Internet

of Things) devices are more complex and more precise than those of the early microcontroller

era. Using this new crop of precision sensors demands a working knowledge of the I2C and SPI

serial protocols. If you are thinking about using sensors with Wi-Fi or Bluetooth, you’ll need to

know how the aforementioned serial protocols work at the bit level. While USB has taken over in

the PC world, you will still need to know how bits are exchanged using the hard-to-kill RS-232

protocol.

■ SCHEMATIC 1. ThePIC’s application firmwarebootloader is initiallyprogrammed using theICSP portal. Applicationprogramming isaccomplished using theCCS IDE and thebootloader.

Eady - Design Cycle - Feb 17_Design Cycle - Sep 15.qxd 1/2/2017 9:50 PM Page 50

Page 51: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

SPI portal, I2C, comparators, timers, a PWMengine, and a USART, it is not designed to supportlarge complex projects. The idea is to use theE3mini hardware to build and code small projectswhose basic elements can be used to fabricatemuch larger projects with PICs that contain largerquantities of memory and GPIO resources.

The E3mini is supported by a companion book(Embedded C Programming by Mark Siegesmund)and a special single-device PIC18F14K50 Ccompiler. The E3mini is geared towards IoTapplication development. A couple of specializedhardware add-on kits (E3mini Advanced AccessoriesKit and Sensor Explorer Kit) that directly supportthe E3mini are also available from CCS.

You can get the wiring layouts of each of theE3mini Advanced Accessories Kit components as aPDF file from the CCS website (www.ccsinfo.com).

There is also a PDF version of the E3miniExercise Book that comes as part of thePIC18F14K50 C compiler. All of the SensorExplorer Kit layouts and application instructions areincluded in the Sensor Explorer for E3mini Exercise Book,which is also installed as part of the PIC18F14K50 Ccompiler package. You can find the PDF versions of theaforementioned books in the datasheet’s folder.

All of the projects for both accessory kits can beassembled on a solderless breadboard. A solderlessbreadboard is included with each kit. Interconnectsbetween the solderless breadboards, sensor devices, andthe E3mini are made using high quality jumpers, which arealso included as components of the accessory kits.

Rather than show each of the kit’s components here,I’ll again point you at the CCS website. There you will findall of the Sensor Explorer and E3mini Accessory kit detailsand photos.

The E3mini architecture can be viewed in its graphicform in Schematic 1, while the three-dimensional versionof our E3mini is captured in Photo 1.

CCS-Supplied FirmwareThe key to utilizing the E3mini hardware lies in

including the e3.h file in your E3mini application code.

The e3.h file is part of the single-device PIC18F14K50 Ccompiler and sees the E3mini hardware GPIOconfiguration in this way:

//// DEVKIT I/O CONFIGURATION //// Pin Analog Port Description //// ----- ----------- -------------------//// RB4 AN10 Header pin 8//// RB5 AN11 Header pin 7 (also

UART RX) //// RB6 Header pin 6//// RB7 Header pin 5 (also

UART TX) //// RC0 AN4 Potentiometer,

header pin 16 //// RC1 AN5 Switch 1, header

pin 15 (also INT0) //// RC2 AN6 Switch 2, header

pin 14 (also INT1) //// RC3 AN7 Red LED, header

pin 13 (also INT2) //// RC4 Yellow LED, header

pin 12 //// RC5 Header pin 11

(also CCP1) //// RC6 AN8 Green LED, header

pin 10 //// RC7 AN9 Header pin 9

#define RED_LED PIN_C3#define YELLOW_LED PIN_C4#define GREEN_LED PIN_C6

#define BUTTON_1 PIN_C1#define BUTTON_2 PIN_C2

The e3.h file also sets up the USB run time definitionsand defines the PIC18F14K50 configuration fuse settings.The bootloader memory extents are also defined withinthe contents of the e3.h file.

The E3mini hardware design includes a piezo buzzer.The E3mini’s buzzer can be driven by a PWM signal

ADVANCED TECHNIQUES FOR DESIGN ENGINEERS

February 2017 51

■ PHOTO 1. The E3mini is based on the low pin countPIC18F14K50. The E3mini’s pushbuttons, potentiometer, LEDs, and

buzzer are connected as shown in Schematic 1.

CCS C CompilerE3mini

Sensor Explorer KitE3mini AdvancedAccessories KitEmbedded C

Programming BookCCS

www.ccsinfo.com

ZMOTION ModuleZEPIR0BAS02MODG

Digi-Keywww.digikey.com

MCP1703Microchip

www.microchip.com

Eady - Design Cycle - Feb 17_Design Cycle - Sep 15.qxd 1/2/2017 9:50 PM Page 51

Page 52: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

derived from GPIO pin RC5.As you can see in Figure 1,

every sensor in the SensorExplorer Kit is supported bysome associated C examplecode. The same is true for theE3mini Advanced AccessoriesKit. Having access to thecanned C routines doesn’t takethe work or fun out of learningC. In this case, the example Ccode happens to be writtenvery elegantly.

The idea is to study theexample C source code andapply the techniques foundwithin the examples to yourown C coding efforts. Forinstance, there are multipleways to access a PIC’s GPIOpins. This statement will turn onall of the E3mini’s LEDs:

output_c(0b01011000);

This set of instructions will illuminate all of theE3mini’s LEDs as well:

output_bit(RED_LED,1);output_bit(YELLOW_LED,1);output_bit(GREEN_LED,1);

We can also turn on the LEDs like this:

output_high(RED_LED);output_high(YELLOW_LED);output_high(GREEN_LED);

If we want to add some pain to our code, we can goaround the mountain like this:

//turn off the LEDsoutput_low(RED_LED);output_low(YELLOW_LED);output_low(GREEN_LED);//turn on the LEDsoutput_toggle(RED_LED);output_toggle(YELLOW_LED);output_toggle(GREEN_LED);

LED EleganceLEDs are most often used as visual indicators. Seldom

would we want to signal an event by illuminating all of theLEDs at once. However, we must plan for such an event.For instance, all of the LEDs may be illuminated as an LEDfunction test at the beginning of a program.

The E3mini is equipped with three onboard LEDs.Three LEDs provide a total of eight possible E3mini LED

states. We’ll enumerate them so we can use human termsas arguments to the LED illumination commands:

enum e3Leds{//arguments states//------------ ------

allOff, //0red, //1yel, //2red_yel, //3grn, //4grn_red, //5grn_yel, //6grn_yel_red //7

};

Now that we can call our LED shots by name, let’s laythe eight E3mini LED binary states out in a flash basedarray:

const char ledBitMap[] = {

0b00000000, //allOff0b00001000, //red0b00010000, //yel0b00011000, //red and yel0b01000000, //grn0b01001000, //grn and red0b01010000, //grn and yel0b01011000 //grn and yel and red

};

Looking at the ledBitMap array, there is one thing thatcomes immediately to my mind. I can simply write thesebit patterns to PORTC and get the job done. There’s onlyone problem with that.

There may be other things attached to the remainingport pins in addition to the LEDs. We certainly don’t wantto be turning other stuff off and on when we access theLEDs.

So, we will need a tricky function that parses ourhuman-readable LED commands and illuminates only theLEDs we specify. Before we code the function, we need todefine the E3mini’s LED bit positions:

#define redLedBit 3 //port pin C3#define yelLedBit 4 //port pin C4#define grnLedBit 6 //port pin C6

The bit position definitions are necessary because wewill use the CCS C built-in bit_test function to determinehow to handle the output of each LED GPIO pin. Let’scode our LED command function and call it ledsON:

void ledsON(int8 selectedLEDS){

output_bit(RED_LED, bit_test(ledBitMap [selectedLEDS],redLedBit));output_bit(YELLOW_LED, bit_test(ledBitMap [selectedLEDS],yelLedBit));output_bit(GREEN_LED, bit_test(ledBitMap [selectedLEDS],grnLedBit));

}

To illuminate the E3mini’s red LED, we would simply

Post comments on this article and find any associated files and/or downloads at www.nutsvolts.com/magazine/article/February2017_DesignCycle_E3mini.

52 February 2017

■ FIGURE 1. The realplus in having prewritten

example code is beingable to study the

elegance in which it isdone.

Eady - Design Cycle - Feb 17_Design Cycle - Sep 15.qxd 1/2/2017 9:50 PM Page 52

Page 53: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

code ledsON(red);. The bit_test function returns alogical high which is passed to the RED_LED GPIO pinby the output_bit function. Logical low signals are sentto the YELLOW_LED and GREEN_LED GPIO pins.Coding ledsON(grn_yel_red); would pass logical highsto all of the E3mini’s GPIO pins that are driving theonboard LEDs.

Blinking LEDs may seem to be atrivial task. However, that’s not thepoint. Check out the SensorExplorer Kit’s ex_sk_7seg_led.cexample file and you will see wherethe elegance of our simple LEDselection application originated.

Motion Sensing withthe E3mini

The Sensor Explorer Kit containsa wide range of sensors. In that allof the kit’s sensors are supported bytext and code, I decided to write anE3mini sensor application using asensor that is not part of the originalkit.

Our E3mini motion sensingapplication will employ the servicesof a Zilog ZMOTION motionsensing module like the one you seein Photo 2. The ZMOTION sensoris very easy to use. All we need to

do is monitor the ZMOTIONmodule’s output pin. When nomotion is sensed, the ZMOTIONoutput signal is held logically high.In this case, logically high is +3.3volts. The E3mini is a five voltdevice.

Since the ZMOTION moduleprovides a signal at its output thatwill be sensed as a logical high byour E3mini, we can directly interfacean E3mini pin to the ZMOTIONmodule’s output pin. TheZMOTION circuitry is also easy torealize.

As you can see in Schematic 2,

February 2017 53

■ PHOTO 2. The Zilog ZMOTION module is a complete PIRsensing system. The motion-sensed output signal falls to a logical

low when motion is detected.

■ SCHEMATIC 2. The ZMOTION module is just aseasy to wire as it is to write code for.

■ SCHEMATIC 3. No rocket science here. It doesn’t get anysimpler than this.

■ PHOTO 3. It ain’t pretty, but itworks. The 3.3 volt regulator isperched on a three-pin SIP header.The filter capacitors are 10 μF at10WV in 0805 packages.

Eady - Design Cycle - Feb 17_Design Cycle - Sep 15.qxd 1/2/2017 9:50 PM Page 53

Page 54: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

wiring a ZMOTION module is a walk in the park. OurZMOTION module is wired to operate in hardware mode.The logic levels on pins 3 and 4 of the ZMOTION moduleset an active-low motion detected output pulse of twoseconds at maximum sensitivity.

We know that the ZMOTION module operates at+3.3 volts. So, we will take advantage of the E3mini’s +5volt voltage rail which is supplied via the VBUS pin of itsUSB interface to supply power to our ZMOTION module.All we need is a simple +3.3 volt regulator that takes itsinput voltage from the E3mini +5 volt source.

The voltage regulator design is outlined in Schematic3. The actual voltage regulator circuit is smiling for theCanon in Photo 3. The +3.3 volt regulator is built up on athree-pin SIP header. The 10 µF filter caps are soldered tothe SIP pins.

The E3mini’s power pins are arranged in such afashion as to perfectly mate to the power rails of asolderless breadboard. In Photo 4, I used a pair of four-pinDIP headers to secure the E3mini to the solderlessbreadboard. One set of DIP headers is soldered to theE3mini’s power pins below the female header and supply+5 volt power to the solderless breadboard’s upper powerstrip.

The other set of DIP headers is supporting the E3minimodule in a nonelectrical way. The physical support DIPheader is mounted in the solderless breadboard power railand supports the E3mini using its pins to pierce the

E3mini’s rubber foot. This provides a stable E3miniplatform when the USB cable is connected to the E3mini.

Our E3mini motion sensing application will build uponthe LED code we have previously written.

When the ZMOTION signals motion is detected, wewill have our application code force the E3mini’s trio ofLEDs to count up in binary during the two second motiondetected pulse. We will also use the E3mini’s USB portalto send an ASCII message to the CCS C built-in terminalemulator.

We’ve already laid the application ground work. So,let’s focus on the code that will actually become theapplication enabler. First, we must extinguish the E3mini’sLEDs and initialize some local variables:

void main(){

int8 i; //general purpose loop //counter variable

int16 motionCnt; //incrementing count of //motion detected events

ledsON(allOff); //turn off the E3mini’s //LEDs

motionCnt = 0; //initialize the event //count

54 February 2017

■ SCREENSHOT 1. The serial input/output monitor is aterminal emulator application that is included with the

CCS C Compiler package. In the case of the E3mini, theterminal emulator is automatically kicked off each time a

successful compile is performed

■ PHOTO 4. The E3mini is supported by a pair of quad DIPheaders. The top voltage rail is five volts, while the bottomvoltage rail is at 3.3 volts. The 3.3 volt voltage rail suppliesthe Zilog motion detector.

Eady - Design Cycle - Feb 17_Design Cycle - Sep 15.qxd 1/2/2017 9:50 PM Page 54

Page 55: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

Now we can concentrate on the main applicationloop code:

while(TRUE){

if(!input(motionIn)) //look for logical //low on RB5

{++motionCnt; //motion detected-

//increment event //count

//send motion detected message to //terminal emulator

printf(“\r\nMotion Detected!\r\n”);printf(“Motion Count = %Lu\r\n”, motionCnt);

//force LEDs to count up in binary every //100mS until RB5 returns to a logical //high

i = 0;do{

ledsON(i++);if(i == 7){

i = 0;}delay_ms(100);

}while(!input(motionIn)); ledsON(allOff);

}}

The ZMOTION will present a logical high signal to theE3mini’s RB5 pin when no motion is detected. So, we willconstantly monitor RB5 for a logical low signal. Whenmotion is detected, the ZMOTION module will drive itsoutput pin low. We see that on RB5 and increment themotion event counter (motionCnt). Using printf, we senda motion detected message which includes the currentmotion event count. The motion detected message iscaptured in Screenshot 1.

Take another look at the e3Leds enumeration code.Note that the LED patterns are organized as binarypatterns with the red LED in bit position 0, the yellow LEDin bit position 1, and the green LED in bit position 2. Thus,to create a binary counter visual using the E3mini’s LEDs,all we have to do is rotate through the ledBitMap arrayfrom 0 to 7.

Our eyes need some delay to distinguish the changesin the LED illuminations. So, we will count in 100 msintervals. The binary rotation of the LEDs is continued untilthe low-going two second motion detected period expires.Once motion is detected again, the process repeats withan updated event count.

C the AdvantagesOnce you begin to study the exercise code and see

the results, you will wonder why you haven’t been doingthings in C all along. Take advantage of the features thatabound within the CCS C compiler. If you have troubleunderstanding how to use a particular PIC peripheral, turn

to the CCS C’s Project Wizard for help. For instance, ifyou wish to produce a PWM signal to drive the E3mini’sbuzzer at 2 kHz, simply open the Project Wizard, setCCCP1 for PWM mode, and enter the desired PWMfrequency with a duty cycle of 50%. The Project Wizardwill present you with this:

setup_ccp1(CCP_PWM|CCP_SHUTDOWN_AC_L|CCP_SHUTDOWN_BD_L);set_pwm1_duty((int16)310);

Insert the Project Wizard code into your application,place a jumper between C5 and spr on the E3mini GPIOheader, and proceed to drive everyone in the room crazy.NV

Explore SENSORS

Sensors Explorer Kit

Includes: E3mini Prototyping Board and C Compiler! AND: • 16 Sensors • 3 Output devices • Getting Started with C Tutorial • Breadboard & Jumpers

Learn Embedded C with the inexpensive E3mini board on the popular PIC® MCU

ONLY

$69

e SEL

ExplorLearn EmbeE3 i i b

ENSORSe

it KerExplors:

with the inexpensivLearn Embedded C PICrd on the popular ® MCU

typing toori Pand C Compiler!ND:• s16 Sensor• vices3 Output de•

lGe

utorialg

h C Twith Ctting Started

• eadboard &BrsJumper

sales@ccsin

v217o.com/nf.ccsinwwwo.com | Sales 262.522.6500 Ext 35fsales@ccsin

v217o.com | Sales 262.522.6500 Ext 35

February 2017 55

Did you know that if you’re a paid subscriber

to Nuts & Volts, you can get the online version

for FREE? Get details at

www.nutsvolts.com

Eady - Design Cycle - Feb 17_Design Cycle - Sep 15.qxd 1/2/2017 9:50 PM Page 55

Page 56: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

CURRENT-SENSEAMPLIFIER

Texas Instruments (TI) hasintroduced a new current-sense

amplifier for in-line motor phasecurrent measurement that improvesoverall motor efficiency compared toexisting current-sense amplifiers. TheINA240 offers enhanced pulse-width

modulation (PWM) rejection forsystems running at up to 80V tosupport a variety of applications suchas motor control, solenoid control,and power delivery systems. Keyfeatures and benefits include:

• Enhanced PWM rejection forimproved motor efficiency: Thepresence of high speed in-line PWMmotor control systems requires high

AC and DC accuracy. The INA240’senhanced PWM rejection improvestransient suppression and givesdesigners the ability to reduce theirblanking time, optimize the motorcontrol algorithm, and ultimatelyimprove motor efficiency.

• Flexible for a variety of motorapplications: The INA240 operates atPWM rates in excess of 100 kHz,with switching-edge rates as high as10 V/ns while enabling systemvoltages as high as 80V. In addition,to address the needs for a widerange of systems, this device supportsthe negative voltages (-4V) inducedby the inductive kickback of themotor.

• Industry-leading performanceand accuracy: The INA240 has oneof the industry’s best combinations oflow offset voltage (5 µV), offset drift(50 nV/°C), gain error, and driftperformance (0.05 percent and 0.5ppm/°C, respectively). The devicealso provides an excellent ACcommon-mode rejection ratio(CMRR) of 93 dB at 50 kHz. TheINA240 delivers performance over awide range of operating conditions.

• Enhanced performance for anymotor control solution: The INA240’sprecision is showcased in a 48V 10Ain-line three-phase high frequencyGallium Nitride (GaN) inverter forbrushless motor reference design.This BoosterPack™ plug-in modulereference design is paired with aC2000™ LaunchPad™ kit,demonstrating how designers can usethe INA240 and LMG5200 GaN half-bridge power stage to reduceswitching losses over an extendedtemperature range up to 125°C,facilitate the use of higher PWMfrequencies, and reduce heatsinkingrequirements.

The eight-pin INA240 is availablein a 3 mm x 4.4 mm thin-shrink smalloutline package (TSSOP). Anevaluation module is available for$25.

Continued from page 17■ NEW PRODUCTS

FREEPCB Layout Software &PCB Schematic Software

DOWNLOAD our free CAD software

DESIGN your 2 or 4-layer PCB

CHECK your design with xCHECK DRC

SEND us your design with just a click

RECEIVE top quality boards in just days

12345

MADE IN THE USA | www.expresspcb.com

$613 PCBs

2-layerMiniBoardPro

(Shipped in 2 business days)

$413 PCBs

2-layerMiniBoard

(Shipped in 1 business day)

+ shipping + shipping + shipping$813 PCBs

4-layerMiniBoardPro

(Shipped in 3 business days)

Now Offering

SMT STENCILS

– Nano Coating available–

For more information, contact:

Texas Instrumentswww.ti.com

56 February 2017

New Products - Feb 17_Mar15 -NV - NewProducts.qxd 1/2/2017 9:45 PM Page 56

Page 57: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

February 2017 57

■ BY CHUCK HELLEBUYCK

It will work with a standard PC PS2 keyboard and VGA monitor. The Maximite has its own built-in SD memory card and the BASIC language embedded in the fi rmware so you can start writing and running BASIC programs right after it powers up.

The Colour Maximite also has 40 input/output (I/O) lines including an Arduino compatible connector. These I/Os can be independently confi gured as analog inputs, digital inputs, or digital outputs. You can measure voltage, frequencies, detect switch closures, etc., and respond by turning on lights, closing relays, etc. — all under control of your BASIC program.

The design and the fi rmware including the BASIC interpreter are free to download and use since it’s an open source design.

I have bought and built several variations of Maximites, but my favorite design is the CGCOLORMAX2 from CircuitGizmos.com. The CGCOLORMAX2 comes almost completely assembled as a circuit board computer. There are a few components you have to solder on, such as a power connector and the optional Arduino headers. You can also add a stereo sound output to connect a speaker. It even has an expansion area for custom circuitry and a spot for CAN, RS-232, and RS-485 chips.

The Maximite design has a real time clock function so the CGCOLORMAX2 includes a battery for that. The Arduino headers were actually something I suggested to Geoff, and many other users added their support of the idea so he added it to the latest design. This makes it easy to use a modern Arduino shield with the old fashion BASIC language.

he original Maximite is a small and versatile single-chip PIC32 based computer

created by Geoff Graham. He followed that up with the Colour Maximite that runs

a full featured BASIC interpreter with 128K of working memory and eight colors on

a VGA monitor (http://geoffg.net/maximite.html). This is like a modern version of the

Commodore 64, Apple II, or TRS-80 computer that I learned to program on.

TMaximite Computer

3D Printed Case

Using 3D printers for practical projects on your workbench.

■ FIGURE 1. Complete Maximite computer setup. ■ FIGURE 2. The CGCOLORMAX2.

PRACTICAL 3D PRINTING

Hellebuyck - 3D Printing - Feb 17.indd 57 1/2/2017 10:48:57 PM

Page 58: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

58 February 2017

away easier. That’s another thing I like about Simplify3D. I can adjust those fine details to get the exact result I want. I also put support in the hole for the audio jack, but then realized it wasn’t necessary and just created a messy hole.

Figure 8 was the test to see if all the dimensions were correct. I obviously needed to make a few adjustments to get a perfect fit, and during the support removal I found the separation posts were too thin and broke away with the support material. So, all that was corrected for the final design.

Final DesignThe final design was printed on

my Flashforge Dreamer 3D printer. It’s my best printer when using ABS plastic. ABS tends to warp and split if it’s cooled too quickly. The Flashforge has an enclosed chamber that traps the heat, and this helps prevent any splitting or warping of the print. The design was printed in two runs; first I did the base and then the cover. The cover was printed upside down, so the slot that fits perfectly over the top of the box didn’t need supports.

ConclusionI am not a design expert by any means but when I

have an idea in my head, I can do a little work in Tinkercad

The Maximite software also has a built-in editor for writing and editing programs. There are third-party applications for loading programs into the Maximite through the USB connector, so you have that option as well.

I wanted more than a bare board sitting on my desk when I use this retro computer, so I decided to 3D print a custom case for it. The case is made of ABS plastic and has slots in the back for the connectors, and a slot in the front for the SD card. It also has slots on top for the Arduino connectors to poke through. The back has the keyboard, VGA, power, USB, speaker, and expansion connector slots.

3D DesignI designed the case in Tinkercad (as usual) which is the

free easy-to-use CAD program that is in the cloud. I like it because I can create a design by just placing different shaped objects together to form the final design; it’s similar to building with LEGO Blocks. I designed the case into two pieces: a bottom box and a top cover that just sets on top, with a groove cut in the bottom side that fits over the bottom box walls to hold it in place.

The bottom box has a lower base or lip that matches the top cover shape. In fact, I created the top and then copied it and placed the copy on the bottom of the base. The base has holes cut out for the various connectors and a slot in front for the SD card. To finish it off, I recessed the name MAXIMITE into the front surface. I later added slots in the top cover for the Arduino connectors to pop through. Figures 3A and 3B were captured before that was added.

I also considered making the top screw down in place, so I extended the mounting holes in the base up through the cover; I didn’t like that design, however. The top

actually sits tightly on the base because the groove cut in the bottom of it (that you can’t see in the graphic) is just barely larger than the base, so I get a friction fit.

SupportsI 3D printed the case in the position

shown in Figure 3, though I printed the cover separately. Round holes tend to print fine

because they gradually change shape, but the rectangular holes have the long flat tops which will result in the plastic material sagging. Figure 4 shows an example of printing without any support underneath. This can be corrected with support material in the slicing software.

The Tinkercad design is exported as an .STL file and then sliced by (you guessed it) a slicing software to create the GCode the 3D printer will run. I prefer to use Simplify3D software for this. One advantage to this software is I can manually place where to put support material that is designed to break away easily.

The red colored blocks are the supports I added to the design before slicing. These will print with the same material as the case; I used a light blue ABS plastic for the final design. The software makes these supports thin so they can easily break away. They are printed in a zig zag fashion despite the block look in Figure 5.

Figure 6 shows my first attempt at making the box with supports. I used a white plastic for this. I printed it in a 0.3 layer height to make it print quicker, and used a far lower 10% fill. This makes the design rougher but produces a great first prototype when finished. The final design will be done at a 0.2 layer height and a more solid fill of 50%, which comes out smoother.

Figure 7 shows the zig zag look of the support. This first attempt showed that I needed to adjust the separation settings in the slicing software to make the supports break

REAL WORLD USES FOR THE ELECTRONICS EXPERIMENTERPost comments on this article and find any associated files and/or downloads at

www.nutsvolts.com/magazine/article/February2017_Practical3DPrinting.

n FIGURE 3A and 3B. Case design in Tinkercad.

n FIGURE 4. No support for holes. n FIGURE 5. Simplify3D support structure.

Hellebuyck - 3D Printing - Feb 17.indd 58 1/2/2017 10:49:11 PM

Page 59: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

February 2017 59

away easier. That’s another thing I like about Simplify3D. I can adjust those fine details to get the exact result I want. I also put support in the hole for the audio jack, but then realized it wasn’t necessary and just created a messy hole.

Figure 8 was the test to see if all the dimensions were correct. I obviously needed to make a few adjustments to get a perfect fit, and during the support removal I found the separation posts were too thin and broke away with the support material. So, all that was corrected for the final design.

Final DesignThe final design was printed on

my Flashforge Dreamer 3D printer. It’s my best printer when using ABS plastic. ABS tends to warp and split if it’s cooled too quickly. The Flashforge has an enclosed chamber that traps the heat, and this helps prevent any splitting or warping of the print. The design was printed in two runs; first I did the base and then the cover. The cover was printed upside down, so the slot that fits perfectly over the top of the box didn’t need supports.

ConclusionI am not a design expert by any means but when I

have an idea in my head, I can do a little work in Tinkercad

and get some help from my 3D printer. I can make custom electronic cases that are far more attractive than notching out an off-the-shelf box (that I did for years). This design required a slightly larger 3D printer, and the Flashforge Dreamer handled this size just fine.

There are so many electronic kits that are already designed and ready to assemble, but don’t come with a

nice case. Having a 3D printer and a little time can change all that. I now look at those kits in a new light because they can be a lot more useful and attractive with a custom designed enclosure. NV

n FIGURE 9. Final design.

n FIGURE 8. Testing of board fit and finish.

n FIGURE 7. Zig zag support.

ResourcesCheck out my website and blog:

www.elproducts.com

My YouTube channel:www.filamentfriday.com

My 3D designs:www.thingiverse.com/elproducts/designs

Tinkercad:www.tinkercad.com

actually sits tightly on the base because the groove cut in the bottom of it (that you can’t see in the graphic) is just barely larger than the base, so I get a friction fit.

SupportsI 3D printed the case in the position

shown in Figure 3, though I printed the cover separately. Round holes tend to print fine

because they gradually change shape, but the rectangular holes have the long flat tops which will result in the plastic material sagging. Figure 4 shows an example of printing without any support underneath. This can be corrected with support material in the slicing software.

The Tinkercad design is exported as an .STL file and then sliced by (you guessed it) a slicing software to create the GCode the 3D printer will run. I prefer to use Simplify3D software for this. One advantage to this software is I can manually place where to put support material that is designed to break away easily.

The red colored blocks are the supports I added to the design before slicing. These will print with the same material as the case; I used a light blue ABS plastic for the final design. The software makes these supports thin so they can easily break away. They are printed in a zig zag fashion despite the block look in Figure 5.

Figure 6 shows my first attempt at making the box with supports. I used a white plastic for this. I printed it in a 0.3 layer height to make it print quicker, and used a far lower 10% fill. This makes the design rougher but produces a great first prototype when finished. The final design will be done at a 0.2 layer height and a more solid fill of 50%, which comes out smoother.

Figure 7 shows the zig zag look of the support. This first attempt showed that I needed to adjust the separation settings in the slicing software to make the supports break

REAL WORLD USES FOR THE ELECTRONICS EXPERIMENTERPost comments on this article and find any associated files and/or downloads at

www.nutsvolts.com/magazine/article/February2017_Practical3DPrinting.

n FIGURE 6. Supports in place.

PRACTICAL 3D PRINTING

Hellebuyck - 3D Printing - Feb 17.indd 59 1/2/2017 10:49:29 PM

Page 60: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

GREAT FOR DIYers!

Programming PICs in Basicby Chuck Hellebuyck

If you wanted to learnhow to program microcontrollers, thenyou've found the rightbook! Microchip PICmicrocontrollers arebeing designed into electronics throughoutthe world and none ismore popular than the eight-pin version. Nowthe home hobbyist can create projects with these little microcontrollers using a low cost development tool called the CHIPAXE system and the Basic softwarelanguage.Chuck Hellebuyck introduceshow to use this development setup tobuild useful projects with an eight-pinPIC12F683 microcontroller. $14.95

Programming ArduinoNext Steps: Going Further

with Sketchesby Simon Monk

In this practical guide,electronics guru SimonMonk takes you underthe hood of Arduinoand reveals professionalprogramming secrets.Also shows you howto use interrupts, manage memory, program for theInternet, maximizeserial communications, perform digital signalprocessing, and much more. All of the 75+example sketches featured in the book areavailable for download. $20.00

Beginner's Guide to ReadingSchematics, 3E

by Stan Gibilisco

Navigate the roadmapsof simple electroniccircuits and complexsystems with help froman experienced engineer. With all-newart and demo circuitsyou can build, thishands-on, illustratedguide explains how tounderstand and createhigh-precision electronics diagrams.Find out how toidentify parts and connections, decipherelement ratings, and apply diagram-basedinformation in your own projects.

$25.00

Python for MicrocontrollersGetting Started with MicroPython

Program your own MicroPythonprojects with ease

— no priorprogramming

experiencenecessary!

This DIY guide providesa practical introductionto microcontrollerprogramming withMicroPython. Writtenby an experiencedelectronics hobbyist,Python for Microcontrollers: Getting Startedwith MicroPython features eight start-to-finish projects that clearly demonstrateeach technique.

$20.00

Electronics WorkshopCompanion for Hobbyists

by Stan GibiliscoIn this practicalguide, electronicsexpert StanGibilisco shows you,step by step, how toset up a homeworkshop so youcan invent, design,build, test, andrepair electronic circuits and gadgets.Electronics WorkshopCompanion for Hobbyistsprovides tips for constructing your workbench and stocking it with the tools,components, and test equipment you’llneed. Clear illustrations and interesting do-it-yourself experiments are includedthroughout this hands-on resource.$25.00

Make Your OwnPCBs with EAGLE

by Eric KleinertFeaturing detailedillustrations andstep-by-step instructions, MakeYour Own PCBs withEAGLE leads youthrough the processof designing aschematic and transforming it intoa PCB layout. You’llthen move on tofabrication via the generation of standardGerber files for submission to a PCB manufacturing service. This practical guideoffers an accessible, logical way to learnEAGLE and start producing PCBs as quickly as possible.

$30.00

How to Diagnose and FixEverything Electronicby Michael Jay Geier

A Fully RevisedGuide toElectronics Repair all kinds ofelectrical products,from modern digitalgadgets to analogantiques, with helpfrom this updatedbook. The SecondEdition offers expertinsights, case studies, and step-by-stepinstruction from a lifelong electronics guru.Discover how to assemble your workbench,use the latest test equipment, zero in on andreplace dead components, and handlereassembly. $24.95

60 February 2017

The Nuts & Volts WEBSTOREFor comple te pr oduct de t ai ls , v is i t us onl ine!!

The Big Book of Maker Space Projects

by Colleen Graves, Aaron GravesStart-to-finish

fun projects formakers of all

types, ages, andskill levels!

This easy-to-followguide featuresdozens of DIY lowcost projects thatwill arm you withthe skills necessaryto dream up andbuild your own creations. Each projectfeatures non-technical step-by-stepinstructions with photos and illustrationsto ensure success and expand yourimagination. Learn recyclables hacks,smartphone tweaks, paper circuits, musicalinstruments, 3-D printing, and much more!$20.00

Arduino: A Beginner's Guide ToProgramming Electronics

byChuck Hellebuyck

Arduino is one of themost popular microcontroller development boardsavailable. It's more thanjust a module though, asthe heart of Arduino isthe software you runon your computer anduse to create sketches(or programs) in the Cprogramming language, with many pre-builtfunctions. Chuck explains all this in verysimple terms to help you get started programming your own electronic applications. His down-to-earth style ofexplaining technology makes it a greatplace to get started with programmingelectronics. $15.00

NV Webstore - Feb 17 working_NV Webstore June 2016 working.qxd 12/30/2016 3:30 PM Page 60

Page 61: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

CD-ROM SPECIALEDUCATIONAL

February 2017 61

Or CALL 1-800-783-4624 today!Order online @ store.nutsvolts.com

NV Webstore - Feb 17 working_NV Webstore June 2016 working.qxd 12/30/2016 3:30 PM Page 61

Page 62: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

62 February 2017

success is knowing and maintaining the proper time vs. temperature profile. The temp ramps up, levels off, and then ramps down all under processor control. Ryan also refers to SparkFun Electronics' Reflow Toaster Controller for toaster ovens. Another reference is to Kester’s SMD soldering time/temp profile (kester.com) and I plan to read it. You should too.

The second least complicated method is analog and manual. If you mount a readily available barbeque thermometer inside your toaster, you’ll be able to raise/lower inside heat and time the temperature transitions with a watch. I understand this not-very-fancy-at-all method and notice my grill’s temp gauge reads up to 700 degrees F. That’s more than enough range to see SMD solder paste melt. My grill’s gauge is a replacement I bought in the BBQ section of a local big box store and is not expensive. Now all I need is patience and a working clock!

Bill GoodRahway, NJ

#4 There are circuits to control a toaster oven to make a reflow oven, but I get decent results using a normal toaster oven and the following procedure:

1) Mark the top of the toaster oven with a Sharpie™ that it is never to be used for food.

2) Use standard tin-lead solder paste, with a low melting point.

3) Get a stencil to help screen the paste on your board. OSH stencils work fine for most hobbyist work (low volume).

4) Once you have placed the components, put your board in the toaster oven, and turn it on to bake at a low temp (~250) and leave for 5-10 min to bake out any moisture.

5) Turn the toaster up to broil, and keep an eye on the board. You

Send all questions and answers by email to [email protected] via the online form at www.nutsvolts.com/tech-forum

R E A D E R - T O - R E A D E RTECHFORUM

>>> QUESTIONSAuto Bell Galloping Dominoes

I have an electro-mechanical gambling machine — Galloping Dominoes — from the company Auto Bell, and would greatly appreciate if someone could direct me to where I could find a schematic. It has a motor that turns four large switch cams and three smaller cams, and has numerous multi-pole relays all interconnected. Thanks!#2171 Randy Grunwell

Suwanee, GA

Radio WhineI have been using a Sony ICF-

9740 AM/FM table radio on my nightstand since 1974. Recently, there is increasing interference on the AM band. It’s not AC “buzz” or “hum” that one would expect from old power supply filter caps; it's more of a high frequency whine — my guess is around 6-8kcs, and it's consistent even when the volume is turned all the way down. I could replace this unit but I would really rather fix it. Any pointers on finding the source of the noise or theories on what might be causing it?#2172 Hubert Casas

Houston, TX

Three-Way LED Flasher I need a simple circuit to

sequentially flash three separate strings of 10 LED lights. Flashing two strings is easy; three is tougher.#2173 Michael Herman

La Quinta, CA

LED Compatibility?I replaced some outside 60W

bulbs with CREE dimmable LED replacements. The lamps are controlled and dimmed using X10 switches. When switched off, the lamps still glow at about 20% and will not shut off completely unless I

use the disable feature of the switch. However, this prevents the timer from automatically controlling the lights. What causes this and is there a fix, or are LED replacements not compatible with X10?#2174 Christoffer Mortensen

Piscataway, NJ

Vehicle DetectorDoes anyone have suggestions

for buying or building a vehicle detector which can be used with the Arduino? I wish to sense and count passing vehicles.#2175 Robert Johnson

Bolton, MA

>>> ANSWERS[#10163 - October 2016]Surface-Mount Oven Controller

I’d like to dive into doing surface-mount projects. I’ve heard of people using a regular toaster oven for soldering. Will an off-the-shelf oven work or is a special temperature controller required for a good result?

#1 For one-sided boards, electric skillets are known to work. You also need a pair of tongs to get the board in and out quickly. If you simply turn the skillet on and wait for it to heat, the flux will burn off before the solder melts. Unfortunately, I presently have a workbench full of boards with components on both sides. For me, it’s back to the soldering iron.

Chip VeresMiami, FL

#2 Toaster ovens are used for surface-mount soldering. Usually, there is a temperature profile that is used. SparkFun Electronics made a kit that you could use to control a toaster oven, but they don’t sell it anymore. You could probably find the temperature profile on the 'net

and do it manually. You can also use a heat gun to solder surface-mount devices by putting solder paste/solder flux on the pads and then heating up the board with the heat gun. I have found this to not be reliable, especially if there are other parts already soldered on the board.

Another way to do it is manually. If the PCB was tinned when it was produced, it is possible to tack down a few key pins on the board and then solder the rest. This requires a very fine tipped soldering iron, very small diameter solder, and a lot of patience, but it has worked for me.

A few other notes. Getting the solder paste/flux onto the board without bridging adjacent pins is tricky. Oftentimes, a stencil mask can be made when the board is produced. They make it easier to get the solder paste/flux down accurately. However, they come in various quality levels with the good ones being higher priced.

Anonomous

#3 I am this very moment seeking the same solution you are for a variety of surface-mount (SMD) projects. I also have a cheap unused toaster oven just waiting to heat things up!

Two temperature control approaches are readily available, with one being more complicated with a PIC processor and other components. I am “old school” and not yet experienced with programming these, but I located a nifty Nuts & Volts article about a toaster oven controller. This article appeared in NV’s June 2008 issue, authored by Kit Ryan, entitled “Oven Flow 1.0.” I just printed the article out after hunting through my .pdf collection of NV. You should give this a read because Ryan covers the essentials of reflow soldering SMD devices. Important for

Tech Forum - Feb17.indd 62 1/2/2017 10:36:51 PM

Page 63: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

February 2017 63

success is knowing and maintaining the proper time vs. temperature profile. The temp ramps up, levels off, and then ramps down all under processor control. Ryan also refers to SparkFun Electronics' Reflow Toaster Controller for toaster ovens. Another reference is to Kester’s SMD soldering time/temp profile (kester.com) and I plan to read it. You should too.

The second least complicated method is analog and manual. If you mount a readily available barbeque thermometer inside your toaster, you’ll be able to raise/lower inside heat and time the temperature transitions with a watch. I understand this not-very-fancy-at-all method and notice my grill’s temp gauge reads up to 700 degrees F. That’s more than enough range to see SMD solder paste melt. My grill’s gauge is a replacement I bought in the BBQ section of a local big box store and is not expensive. Now all I need is patience and a working clock!

Bill GoodRahway, NJ

#4 There are circuits to control a toaster oven to make a reflow oven, but I get decent results using a normal toaster oven and the following procedure:

1) Mark the top of the toaster oven with a Sharpie™ that it is never to be used for food.

2) Use standard tin-lead solder paste, with a low melting point.

3) Get a stencil to help screen the paste on your board. OSH stencils work fine for most hobbyist work (low volume).

4) Once you have placed the components, put your board in the toaster oven, and turn it on to bake at a low temp (~250) and leave for 5-10 min to bake out any moisture.

5) Turn the toaster up to broil, and keep an eye on the board. You

will be able to see when the solder melts and begins to flow. I usually wait 20-30 seconds after I see the solder begining to flow, then turn off the toaster oven.

6) Open the door and allow the board to cool for 5-10 min before moving it, then take it out and let it finish cooling on your bench.

Mark SauerwaldTacoma, WA

[#10164 - October 2016]iPod Charge Dilemma

I have a USB charger that works with my cell phone but it won’t charge my iPod. Is there something “special” about the Apple iPod charger and if so, can I modify a “regular” charger to work with both?

#1 iPods require voltages on the data pins of the device in order to charge. If your charger has just the positive and negative pins connected to the plug, your iPod won’t charge. This is probably the case. Search the Internet for USB charger circuits.

The modification will require four resistors wired from ground (negative) to positive as voltage dividers. One pair for Data + and the other pair for Data -. According to the circuit diagram I found, you will need two 27K resistors, a 22K, and a 39K. The two 27K resistors are wired to ground (negative) pin 4 on the charger plug. The 22K and 39K are wired to the positive pin 1 on the charger plug. The junction of the 27K and 39K divider is wired to pin 2 (Data -) on the charger plug. The junction of the 27K and 22K divider is wired to pin 3 (Data+) on the charger plug.

Also, for an iPod you should have a charger capable of at least two amps output. The wimpy one amp chargers will take a much longer time to charge Apple devices like an iPod. To be sure which pins are which, just

do a search for USB pinouts.Richard Washburn

Naguabo, PR

#2 In order for the iPod to charge using any USB charger, you need to use a small adapter.

Apparently, Apple chargers have a resistor between the two data pins inside the charger. I had a similar issue when trying to use a non-Motorola or car charger with the Razor V3M phone. A small adapter does the trick and makes the device think a genuine charger is connected.

You can get one here: www.boxwave.com/apple-ipod-nano-3-travel-chargers/apple-ipod-nano-3-ipod-charging-adapter/bwpdd/fpz-gcgz/

Bruce BubelloApex, NC

[#10165 - October 2016]Arcade Game Restoration

I’m refurbishing a vintage video arcade game. There is a transformer between the video monitor and the mains power but it measures as open. From the schematic, it seems to be a simple 115 VAC 1:1 isolation transformer. Is an isolation transformer necessary when the entire cabinet is wood, or is it overkill?

The isolation transformer is for protecting the MAIN METAL PARTS of the arcade machine from electric shock — specifically the coin-handling mechanism. If you’re not going to use the coin machinery (i.e., replace it with a switch or similar), then you could probably get away with not using the line isolation transformer. HOWEVER, consider integrating EMI/RFI/surge protection on the AC power input to help the machine live a little bit longer.

Ken SimmonsAuburn, MI

>>>YOUR ELECTRONICS QUESTIONS ANSWERED HERE BY N&V READERS

Send all questions and answers by email to [email protected] via the online form at www.nutsvolts.com/tech-forum

and do it manually. You can also use a heat gun to solder surface-mount devices by putting solder paste/solder flux on the pads and then heating up the board with the heat gun. I have found this to not be reliable, especially if there are other parts already soldered on the board.

Another way to do it is manually. If the PCB was tinned when it was produced, it is possible to tack down a few key pins on the board and then solder the rest. This requires a very fine tipped soldering iron, very small diameter solder, and a lot of patience, but it has worked for me.

A few other notes. Getting the solder paste/flux onto the board without bridging adjacent pins is tricky. Oftentimes, a stencil mask can be made when the board is produced. They make it easier to get the solder paste/flux down accurately. However, they come in various quality levels with the good ones being higher priced.

Anonomous

#3 I am this very moment seeking the same solution you are for a variety of surface-mount (SMD) projects. I also have a cheap unused toaster oven just waiting to heat things up!

Two temperature control approaches are readily available, with one being more complicated with a PIC processor and other components. I am “old school” and not yet experienced with programming these, but I located a nifty Nuts & Volts article about a toaster oven controller. This article appeared in NV’s June 2008 issue, authored by Kit Ryan, entitled “Oven Flow 1.0.” I just printed the article out after hunting through my .pdf collection of NV. You should give this a read because Ryan covers the essentials of reflow soldering SMD devices. Important for

Tech Forum - Feb17.indd 63 1/2/2017 10:37:07 PM

Page 64: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

circles. Perhaps the masses think of electronic as moresophisticated than electric.

Bryan Bergeron

Readdressing Addresses

Jon Titus’ article about a CAN bus in the December2016 issue was interesting and informative, but hisstatement that the 11-bit CAN ID is a device ID —indicating the ID of the device on the bus that will acceptthe word — is incorrect. The 11-bit ID is a word ID andpriority indicator. Many devices on the bus may use thedata from the same word.

As an example from the automotive world, manydevices may use the vehicle speed information sent out bythe ABS controller. These include the instrument cluster(for the speedometer), the audio system (for speed-sensitive volume control), and the navigation system (todetermine when certain drive inputs are allowed).

Karl HutchinsonAmherst, NY

Karl is correct. CAN devices do not have fixed IDs oraddresses. I should have clarified this in the first article andnot used "address" so loosely. Here's a better explanation.(The other two parts of the CAN bus series also cover IDs.)

All CAN devices on a bus receive every message, andevery message includes a cyclic redundancy-check (CRC)value. All bus devices calculate a CRC value based on themessage data. Then, the bus devices compare theircalculated CRC value with the CRC value sent in themessage. A mismatch indicates an error, and otheroperations come into action.

However, just because all bus devices receive everymessage doesn't mean they need the data in thosemessages. Microcontroller code could run in a continuousloop to compare every message’s ID value with a set ofuser-determined values. When a match occurs, the MCUwould take the message data and use it. This inefficientprocess can take a lot of CPU cycles from other tasks.

As an alternate, CAN bus controllers include masksand filters that alert a CPU only when the controllerreceives messages with specific ID values, say; 0x019 or0x052, or with ID values in a given range; say, 0x020--

0x030. The masks andfilters determine whichdata gets through acontroller, and cangenerate an interrupt.

In effect, the CANcontroller responds only tomessages with specific IDs,which I misrepresented asaddresses. Programmerscontrol the filter and masksettings for specific devicessuch as speedometers,entertainment systems, andso on.

I hope this informationhelps correct themisinterpretation of CANbus "addresses."

Jon Titus

ROBOTICS

E-BOOKS AUDIO/VIDEO

CLASSIFIEDS

Save $10 on $100 order at parts-express.com!

Promo code: NVJ7T*Offer expires 3/31/17

parts-express.com1-800-338-0531

Tools and Tech Aids

Project Accessories

Speakers

Components

LIGHTING

HARDWAREWANTED

www.nutsvolts.comSubscribe today!

READER FEEDBACKContinued from page 7

64 February 2017

DEC and VMEEquipment WANTED!Digital Equipment Corp

andMotorola VME Systems

and PartsBuy - Sell - Trade

CALL KEYWAYS 937-847-2300

or email [email protected]

Reader Feedback - Feb 17_Dev Perspectives - ReadFeed Feb15.qxd 12/30/2016 2:50 PM Page 64

Page 65: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

February 2017 65

Accutrace ................................3

Actuonix Motion Devices ........7

All Electronics Corp. .............44

Anaren ...................Back Cover

Bench Werx ..........................23

CCS ......................................55

Chaney Electronics .................5

Command Productions ...........9

EarthLCD ..............................17

ExpressPCB .........................56

Hammond Manufacturing .....11

Hitec .......................................2

PanaVise ..............................15

PoLabs ...................................7

Saelig Co., Inc. .....................66

ServoCity ..............................67

SDP/SI ..................................17

Technologic Systems ............15

BATTERIES/CHARGERSHitec ...............................................2

BUYING ELECTRONICSURPLUSAll Electronics Corp. ..................44

CIRCUIT BOARDSAccutrace .......................................3ExpressPCB ..............................56Saelig Co., Inc. ..........................66

COMPONENTSAll Electronics Corp. ..................44Chaney Electronics ........................5Saelig Co., Inc. ..........................66ServoCity ......................................67SDP/SI ..........................................17

DESIGN/ENGINEERING/REPAIR SERVICESAccutrace .......................................3ExpressPCB ..............................56

DEVELOPMENTPLATFORMS/TOOLSAnaren ........................Back CoverCCS ..............................................55Technologic Systems .................15

EDUCATIONCommand Productions ...................9

PoLabs ...........................................7

EMBEDDED SYSTEMSSaelig Co. Inc. ...........................66Technologic Systems .................15

ENCLOSURESHammond Manufacturing .............11

LCDs/DISPLAYSEarthLCD ......................................17Saelig Co., Inc. ..........................66

MICROCONTROLLERS /I/O BOARDSTechnologic Systems .................15

MISC./SURPLUSAll Electronics Corp. ..................44

MOTORS / MOTORCONTROLActuonix Motion Devices ................7Hitec ...............................................2ServoCity ......................................67SDP/SI ..........................................17

ROBOTICSActuonix Motion Devices ................7Chaney Electronics ........................5Hitec ...............................................2ServoCity ......................................67

SDP/SI ..........................................17

SENSORSCCS ..............................................55

TEST EQUIPMENTChaney Electronics ........................5

PoLabs ...........................................7

Saelig Co., Inc. ..........................66

TOOLSBench Werx ..................................23

CCS ..............................................55

PanaVise ...................................15

PoLabs ...........................................7

TRANSFORMERSHammond Manufacturing .............11

WIRE, CABLE AND CONNECTORSAll Electronics Corp. ..................44

WIRELESS PRODUCTSAnaren ........................Back Cover

Technologic Systems .................15

ADvertiser INDEX■ L O O K F O R ■ S E A R C H F O R ■ F I N D Find your favorite advertisers here!

ELECTRONETFor the ElectroNet

online, go to

www.nutsvolts.comclick Electro-Net

www.dlpdesign.com

Add USB to your next project--It's easier than you might think!USB

USB-FIFO USB-UART USB/Microcontroller BoardsDesign/Manufacturing Services AvailableRFID Readers

Absolutely NO driver software development required!

ElectroNet - Index - Feb 17_Mar15 -NV - NewProducts.qxd 12/30/2016 3:32 PM Page 65

Page 66: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

• Saelig Company, Inc. • www.saelig.com • [email protected] • 1-888-7SAELIG •

More Unique Products

Signature Analyzer• Controlled via USB

• 5-in-1 Functions

• Includes OscilloscopeAWG, I/O

• WIN, MacOS, Linux

• Under $400

Oscilloscope, Waveform Generator, Digital I/O Port - All in One!

• Terrific educational toolwith lessons/experiments

• AWG, I/O, PWM, FFT

• $99.95

SDS1102X Scope Free Serial Decode Option

• 1GSa/s Sampling• 14 Mpts Memory

• FFT

• 8” LCD

• 60,000 wfm/s

• $424

Wide Selection of Spectrum Analyzers

• Desktop to USB stickversions cover up to12GHz to find signalqualities or interference

• Starting at $518

Power Supplies - 30W to 1500W• Desktop to

rack-mount powersupplies to fit almostany need.

• Programmable on/offvoltage level cycles

• From $56

PCB Repair Equipment• Repair, don’t throw

away costly PCBs.BoardMaster systemsare easy-to-use andcan be used byanyone to find andrepair PCB faults.

EMC Precompliance Testing• Check your PCB

design beforeexpensive formaltesting to makesure you’ll passEMC specs withour affordablesolutions.

Wide Selection of Spectrum Analyzers

• Starting at $518

Automotive Diagnostic Equipment• Picoscope test kits

are designed to makediagnosing & testingvehicle electronics,components easy.Find faults fast!

SIG-101 CGM-101

Full Page.indd 66 10/3/2016 5:36:56 PM

Page 68: Cutting Corners, Without Compromise!ebook-dl.com/magazine/nuts-and-volts-february-2017366.pdf · Using RGB LED Strips and Hall ... into a CCS E3mini. ... paces and code up a sensor

“More coffee Rex!”

Scan the code to learn more and register for a chance to win a free Atmosphere MSDK!* A giant, coffee-carrying,

Cloud enabled, IoT dinobot at the command of your index finger? Why not. In fact, wherever your imagination leads you, Anaren empowers you with the industry’s easiest - to - use wireless connectivity platform. Think. Build. Connect.

* Must be 18 to participate. No purchase necessary. North America only. Void where prohibited. Other restrictions apply. www.anaren.com/air/win

Dino ad fullpage 12-16.qxp_Layout 1 12/20/16 12:05 PM Page 1

Full Page.indd 68 1/2/2017 5:08:06 PM


Recommended