Wednesday, March 16, 2022

Widget Wednesday: Simple Switches

Okay, so I lied last time.  In 20/20 hindsight, it would be rude to dump my Gentle Reader into the world of analogue before discussing binary.  Which, of course, is what switches are all about.  And the majority of potential inputs (and all of the outputs) on an Arduino are binary.

First things first:  What is it good for?  In the proverbial nutshell, a switch controls whether or not current flows through a circuit.  In electronics parlance, it's HIGH or LOW. No nuance -- the current is either ON or OFF and we (mostly) don't care about how much.  For the purposes of micro-controller units (MCUs), I'm going to talk about switches as sensors.  All the MCU needs to know is "Is current flowing to this pin when I check it?"

Switches can be incredibly fancy -- to the point where it's easy to forget that they're switches under the hood.  Eventually, we'll take a deeper dive into widgets like ultrasonic range-finders and DHT (Digital Humidity & Temperature) sensors, which pulse data in the form of micro- or milli-second bursts of ON and OFF.  But as an introduction, we're going to look their much simpler, entirely mechanical, cousins.

Example 1:  Reed Switch

 


First things first:  What is it good for?  Basically any project where you need  to detect a magnetic force within a small radius.  (Depending on the strength and orientation of the magnet, you can figure 10cm as a maximum.)

This is probably the simplest one in my stash and has a delightful old-school retro-sci-fi vibe.  It's also a little more straightforward to understand.  For tasters, it's transparent -- literally and figuratively.  Basically, it's comprised of two ends of a switch hermetically sealed inside a tiny glass bubble.  One of those ends is susceptible to magnetic force.  

When an appropriate magnetic force -- in our case, the pull from a rare-earth magnet -- is applied, the switch opens or closes, depending on both its design and the polarity of the magnetic force. 

Reed-switches come in two flavours:

  • Normally Open -- i.e., by default the two ends do not touch and have to be pushed together by a magnet. 
  • Normally Closed -- i.e. the ends touch by default and have to be forced apart by a magnet.

Of the two styles, the Normally Open (abbreviated "NO") version is more useful when you're trying to conserve battery power.  But there are definitely useful cases for the Normally Closed (NC) style, namely in something known as a "deadman switch."  There, the switch is watching for a drop of current from some source to indicate that, for instance, a door is open.

Example 2:  Momentary Push-button

 


 First things first:  What is it good for?  Very brief human interaction:   "Reset" buttons, console buttons, highly un-ergonomic keyboards.

This form-factor should look pretty familiar; it's the kind of button you smash for video games or hold down and count alligators to reboot your laptop.  Depending on how you wire your project, these can be configured as Normally Open or Normally Closed. 

Our human model of this kind switch probably runs something like this:  Somewhere in the middle of the switch's descent from up to down (or back), the switch crosses a decisive cut-off point between Closed and Open.

Only that the Laws of Physics(TM) plus the realities of mass-manufacturing make that hypothesis more...interesting.  Especially when combined with our human reflexes.  Compared to micro-controllers like the ones that go into Arduinos, we humans are about as responsive as a tree-sloth on quaaludes (thanks, Dave Berry!). 

When the MCU is checking the button's ON/OFF state hundreds or thousands of times per second, what we in Meatspace(TM) perceive as "instantaneous" is a quasi-eternity of quantum ambiguity for the micro-controller.  

Mainly because, with these inexpensive buttons, we're not actually making an unambiguous downward/upward movement.  That "springiness" we feel in the button translates to a semi-random sequence of ONs and OFFs that rivals the relationship status of celebrity couples by orders of magnitude.   

Hardware-wise, you might be able to work around it with higher-quality switches and maybe some current-dampening via a resistor.  In this case, you're better off with fixing it at the software level with what's known as "de-bouncing code."  At some point, I will do a deep-dive into momentary push-buttons with a de-bouncing code example.  Just not today.

Example 3:  Latched Push-button

 


 This version of a push-button should also be familiar, except that once the button snaps into the "down" state, it stays there ("latched") until it's pressed again.  

First things first:  What is it good for?  Human interaction, but mainly in a set-it-and-forget-it way. 

Again, from the micro-controller's perspective, the transition from "Latched" to "Unlatched" will not seem so binary.  And thus will still require some amount of de-bouncing code to handle the ambiguities of being smooshed by apes with social media accounts.  The main difference, of course, is that once the switch "clicks' into place it's set.  That removes some -- but not all -- ambiguity.  From a software perspective, it's best to treat momentary and latched push-buttons more or less identically in code.

But this particular model packs one extra feature in that it has six pins vs. the four of the "momentary" style.  Which, for all practical purposes, allows you to switch two circuits with the same button.  Which, as we'll eventually see, opens up all sorts of possibilities.

Before then, however, I do need to cover the fundamentals of resistors and the basic algebra that goes into pretty much any home-brew circuitry.  Until then:  Tchein ton siault d'beluets!

Wednesday, March 9, 2022

Widget Wednesday: Breadboard Power Supplies/Adapters

First things first:  What is it good for?  Supplying a even flow of DC (direct current) to your electronics project at an expected voltage.  ("A clean signal" is the term my favourite electronics repair folks like to throw around.)  Granted, this seems pretty obvious on the surface but we tend to take that "even flow" part for granted.  Fiddling with electronics -- particularly micro-controllers (MCUs) -- will likely change that.

For relatively simple electronics (e.g. LEDs), it's likely you wouldn't notice that its power supply's voltage level is dropping for a few milliseconds at a time because the human eye can't perceive that.  Micro-controllers, in contrast, live microsecond-to-microsecond.  A voltage-drop on an input circuit can be interpreted as a sensor being tripped.  A voltage drop on the MCU's "Reset" pin will reboot the code uploaded to its memory.

With batteries, these fluctuations generally aren't so much an issue as what happens when the voltage level drops too low.  Power supplied by an outlet can be another story but, barring outages, you should only have to worry about this at setup time.  (For today's purposes, we're going to rule out any solar-/wind-powered project that doesn't have a rechargeable battery in the mix.)

Let's talk about batteries, though.

Pros:

  • Project not tied to an outlet.
  • Shouldn't require additional electronics to "clean up" the signal.
  • Lithium-Ion and AA, AAA, 9V rechargeable batteries (and a charger) are easy to find & inexpensive relative to the long-term cost of non-rechargeables.
  • Calculating current consumption is a good kick in the shins for reading the datasheet.

Cons: 

  • Require a way to monitor for low battery.
  • Project downtime while swapping in freshly-charged batteries.
  • Rechargeable AA and AAA cells operate at a different voltage level than alkaline equivalents.  (Grrrrr...)
  • Not rated for temperatures below the freezing-point.

Personally, I lean on rechargeable NiMH (Nickel Metal Hydride) AA and AAA batteries for everyday electronics anyway, so the up-front cost of the batteries and the charger made sense.  One trip to Canadian Tire and done.  

AA battery-holders are a common form-factor and come in a variety of capacities:  1, 2, 3, 4, and 6.  The holders are dirt-cheap and the ends of the positive and negative leads are generally pre-stripped.  Which means that they, in a pinch, can be jammed directly into the positive and negative power-rails of the breadboard.  I absolutely do not recommend that -- mainly because you don't have to do it too many times before you mangle the ends.  For breadboard prototyping purposes, you (or your favourite electronics repair shop) can solder the raw end of each tip to one end of something called a "male header-pin," and cover the solder-point with shrink-tubing:

 



Again, this is an option only for the prototyping phase of a project.  For a project in active use?   Just don't.  I stone-cold mean it.  That's beyond too dangerous.  The "ground" wire coming loose is bad enough; the "positive" wire coming loose means that anything within its range can become its ground wire.  That includes you, bee-tee-dubs.  And both?  [shudder]  (The possibility of two loose wires at once is why I like to cut positive leads longer than the negative leads.  It's not stupid-proof, mind you, but a little extra insurance doesn't hurt.)

That's where something called a breadboard power adapter comes in.  A power adapter is separate from a power supply in that it outputs a DC current but does not generate it.  Its header-pins seat into the breadboard at least an order of magnitude more securely the ends of the battery pack's leads.  (Sometimes securely enough that seating/unseating the adapter risks bending/breaking header-pins if you're too forceful all at once.  This is particularly common with new breadboards.)  

In addition to securing the power connection to your breadboard, adapters offer amenities such as:

  • Smoothing out ripples in the current.  Maybe.
  • Providing a "standard" socket (e.g. barrel-jack, USB, JST).
  • Providing a specific voltage-level (e.g. 5V, 3.3V).
  • (Possibly) including an On/Off switch (something you'll appreciate when the project is in use).

Let's look at a few examples, with their strengths/weaknesses.

 

This model allows you to power your breadboard via either a 2.1mm barrel-jack or a USB-A male connector.   USB generally standardises on 5V.  The barrel-jack gives you more flexibility which we'll get to in a bit.  Either way, you should figure on your project consuming no more than 500mA of current at any given time.

 


On the plus side, this style is fairly inexpensive, despite basically being the Cadillac of breadboard power adapters.  For mixed-voltage projects, you have the option of powering one side at 5V and the other at 3.3V (a.k.a. 3V3) via jumper-blocks (the yellow rectangles on the left and right).  

On the downside, this form-factor is a pig for space.  On a full-size breadboard, this will probably be negligible.   Half-size breadboards, on the other hand, might require you to break out your Tetris skills.  But their biggest drawback, by far, has been their quality.  My first batch of five came with one D.O.A. and another bricked the first time I pressed the power-button and heard a fateful "snap" in place of the usual springy "click."  (Which is a clue to why I tend to buy them five at a time*.) 

And, even with higher-end power-supply, they have a tendency to just wear out over time.  In fairness, I use these 24/7 in production, rather than occasional prototyping.  

Right.  I promised to get back to the barrel-jack power-supply and voltages.  As I mentioned, USB pretty much comes with 5V baked in.  (Although of course you're going to double-check with your multi-meter, riiiiiiiiiiiight?!?!?!)  The barrel-jack is engineered to expect something more than 5V and step it down.  Now, if your project is based on 3V3, 5V should probably be okay.  But I've had brown-outs with a 5V wall-wart -- a decent-quality one, too.  Switching to 9V made that problem go away.

Oh, and before I forget -- make sure your breadboard positive and negative power-rails match the adapter's +/- labels.

 

 

This model functions much the same.  Fewer bells and whistles mean that it takes up less breadboard space.  Same 2.1mm barrel-jack, but the USB connector is a USB-C (a.k.a. "USB micro").  The tiny black slider-switch in the middle toggles between 5V and 3V3 for the entire unit.  In other words, both breadboard power-rails operate on the same voltage; you can't cherry-pick like the above model.

To be honest, I have really only used this model for mockups & prototyping, not a Boarduino workhorse.  So I can't speak to to the overall quality or longevity of this model.  As with its heftier counterpart, make sure that its +/- pins match the red and blue stripes on the power-rails of your breadboard**.



Okay, this is basically a hack.  The (Sparkfun) breakout board attached to the mini-breadboard is technically meant to interface with all five potential wires of a USB connection.  But that doesn't mean that you can't ignore the middle three pins and use the 5V VCC (positive DC voltage) and GND (negative DC voltage) for your own nefarious (and squee) purposes.

Like all hacks, this is a use-at-your-own-risk kind of deal.  Most notably, there is absolutely no reverse-polarity protection.  You mix up positive and negative?  The "magic smoke" (or worse) is all on you.  This will also not doctor the electrical input.  Whatever voltage is input will be output.  And, probably more important for project stability, there is zero current conditioning -- it will not smooth out drops in voltage or protect you from brown-outs.  Now, if you power your project from, say, the USB port on your laptop, this shouldn't be an issue.  (Or if it is, you have bigger issues.)  Anything else is up to you and your electrical engineering know-how (or lack thereof).

There are other form-factors for these power supplies.  Adafruit, for instance, offers one with adjustable output voltage; Sparkfun offers a beefier version of the mini-supply.  This is just what I have in my stash at the moment.

Mostly, I've been talking about breadboard adapters in terms of power provided by an outlet via a wall-wart.  2.1mm barrel-jacks tend to be the standard (in North America, anyway).  (You might be able to find a wall-wart with a USB-micro connection, but normally you want to save those for your Raspberry Pi)  The prevalence -- meaning re-usability -- of the 2.1mm jack, however, is why I would make the rare argument for splurging on higher-end models.  The current/voltage that comes from our outlets can be shockingly (pun intended) sloppy.  That's why any serious electronics -- including the better wall-warts -- are engineered to clean up the signal. 

 



For battery-powered options, I'd tend to opt for the longevity and and sheer capacity of a Lithium-Ion power stick over NiMH rechargeables.  All other things being equal, of course.  Your project specs -- milliamp-hours of current, size, temperature, etc. all have to be factored the trade-offs that are engineering.

I'm too lazy to double-check my notes, but I think that the next installment will start to tackle resistors.  Until next time, Tchein ton siault d'beluets!

- - - - - 

* If that looks like red nail polish on the barrel-jack, you're absolutely correct!  This adapter's USB power-supply is the only functioning input.  So the red is intended to distinguish this particular unit from others.  See what I mean about this style being notoriously flakey right out of the box? :~/

** Yes, breadboard plastic can get that yellow.  ABS plastic does that.  This workhorse saw some kilometers as the "brains" of a project in continuous service for a couple of years.  I've since learned to be more mindful about distributing current-load, trust me.

Wednesday, March 2, 2022

Widget Wednesday: Wiring

 First things first:  What is it good for?  Actually, two things:

  1. Connecting widgets to the tie-points (i.e. holes, a.k.a. "pins") on a breadboard
  2. Connecting the breadboard tie-points to each other to make complete circuits

 For "Boarduino" purposes, there are two (realistic) options:

  • Flexible jumper-wire
  • Solid-core AWG wire

Let's break down the differences, which are almost-but-not-quite diametrically opposed.

  • Flexible wire is ideal for prototyping.
  • Flexible wire is also fine when you have to connect a breadboard-hostile widget to your project.
  • Solid-core AWG wire is what you use to connect breadboard pins for a project in full-time, real-world use.

In case it isn't obvious right now, you're going to want a mix of both kinds in your kit.

Flexible jumper-wire:  This is made for prototyping and not real-life.  Mostly.  The exception is when the widget doesn't actually plug into the breadboard.  That situation might or might not come with additional issues.  We'll get to those in a bit.

This kind of jumper-wire, under the coloured plastic coating, is actually a bunch of very fine copper wires.  Which is is less likely to break.  But, in my experience, it does like to degrade.  

"War-story":  I was experimenting with something called a Serial-to-Parallel chip to try and control 8-16 LEDs with an Arduino by way of three wires.  Problem was that one of the wires was going wonkier by the minute.  Well, no.  Problem was that I'm a programmer by trade.  So if anything goes wrong, my first instinct is to blame my code.  (Second instinct is to blame file/folder/network permissions, but that doesn't apply here.)

Ultimately, I had the great, good luxury of having an extra breadboard and enough extra widgets to duplicate my setup.  The second version worked flawlessly.  So I methodically replaced each wire in the original breadboarding project and realised that I had a bad one.  The wires weren't even that old, but it's not like they come with an UL rating, either.  So lesson learned.  (End of "war-story.")

Back to those "additional issues."  Off the top of my head, I can think of two widgets that I can only describe as "breadboard-hostile."  One is a common version of the passive infrared (PIR) sensor.  There are two of them below, so that you can see the underside and top-side of the unit.  The top-side (right side) is the lens that acts sort of like an eyeball; the brains -- including the header-pins that connect the sensor to the rest of your project are on the bottom of the board (left side).

The header-pins are the yellow bits near the middle of the pair.  Solid, clearly-labeled header-pins...blocked by two capacitors.  (If you don't know what capacitors are, don't worry; we'll get to that, too.  Just not today.)  

Everyone associated with this board's design is a jerkface.  Not only can you not plug this widget into a breadboard, even a printed circuit-board would have to be designed around this layout-felony.  

It doesn't have to be this way.  The first PIR sensor I ever ordered certainly wasn't this way.  But some slovenly, bean-counting dweeb decided that their rat-race-to-the-bottom retailers could shave $0.00000000000001 off the cost of each unit by massively inconveniencing their customers.  A pox and a plague and a sock-eating dryer upon everyone responsible for this travesty.  (Did I mention that these people are jerkfaces?)

Anyhoo.  Sometimes this sort of stupidity can be turned into a virtue.  But in this case it was only because I had a variety of jumper-wires on-hand.

As some of my Gentle Readers know, my very first real-world Arduino project was designed to teach our omnivorous ElderCat to stay off the counters. 

And, while Mister Kitty is not exactly the sharpest tool in the shed, it only took it three rounds with this thing to convince him that his hoomins were onto him.  (After ten years of yelling and squirt-guns and locking him in the basement after hearing the tell-tale "thump" of his paws hitting the kitchen floor, you're darned tootin' I'm patting myself on the head for that breakthrough.)

The mechanics of this setup are pretty straightforward:

  • Top right is the Arduino-ish Adafruit "Trinket" that is the brains of the outfit.
  • The green board at the bottom-left is a passive infrared (PIR) sensor that detects deviations from the ambient temperature (i.e. a warm, moving body) w/in 3-4 meters
  • The black button is a piezzo buzzer -- a crude audio speaker.

When the PIR sensor detected a warm body in motion w/in the 3-4 meter range, the Trinket fired off a sequence of timed electrical pulses which made the piezzo buzzer play Looney Tunes Tweety-Bird's "I Taught I Taw A Puddy-Tat."  And -- dude! -- it was loud.  Which, of course, was the point.



 

But at the time, we hoomins weren't certain that it would be that easy to convince Mister Kitty that he was being watched.  Also, it didn't take much for either of us to trigger this thing.  And we probably levitated as much as Mister Kitty.  Clearly, we needed a bit more precision.  So I added something called an ultra-sonic range-finder, which acts somewhat like a bat's echo-location.  

In the Mark II version, the PIR sensor detected a warm body moving somewhere in that 3-4 meter range and only then did the Arduino trigger the range-finder to determine whether there was a solid body within a half meter or so away.  Only when those two conditions were met would the piezo element sing its loony-tune to tattle.  

Muuuuuch less levitation on the part of the hoomins.  And after a month or so, the Mark II followed its predecessor into honourable retirement.



Problem was, the 2nd PIR sensor I bought came with that obnoxious, breadboard-hostile layout.  Which is why, in this case, you see it attached to the rest of the project via an umbilical cord of jumper-wires.  But it turned out to be the proverbial blessing in disguise in that also gave us more flexibility in how we could orient the PIR sensor and the ultrasonic range-finder.  Otherwise, we'd be limited to 90-/180-/270-degree angles.  There might be folks in this world with such geometrically-pure lines of sight on their kitchen counters.  Those people are psychopaths who Doordash all three meals. ;~P

And, as much as an chick raised as an anglophone during the 1970s rolls her eyes at the notion of anything under the sun -- including electronics and language -- being gendered, flexible jumper-wires are labelled with three gender-pairings [thumbs nose].  

  • M/M wires have "male" (i.e. solid wire) headers on both ends.  Because they cover at least 90% of prototyping, you will likely get far, far more mileage out of these than the other two kinds.  Stock up accordingly, 
  • M/F wires are...hermaphroditic.  A solid wire on one end and a matching socket on the other. Again, sometimes you need to connect widgets off-board; these are your play.  Those both came into play with the examples above.  Again, stock up accordingly.
  • F/F have the socket on both ends.  Thus far, I can't recall needing any.  But I can recall being a few $CDN short of the threshold for "free" shipping, and so the small handful I have were basically "free." [shrugs]

Regardless of form-factor, jumper-wires (like the solid-core wires we'll be talking about shortly) come in a rainbow of colours.  In the language of electrical engineering, a few colours matter.  Like far too many other things, which country/region you live in determines the norm.  In this (Canadian) series, we're dealing exclusively with two colours/functions:

  • Red == Positive
  • Black == Ground (functionally equivalent to Negative for our DC purposes)

Norms (and consistency) matter -- particularly when you need someone else's help debugging a layout.  Beyond that, it's up to personal preference.  Shocking precisely no one, I have a couple of those:

  • The "warm" colours (orange, yellow, white) I use for "output."  In practice, that means things like lighting up an LED, buzzing a Piezo element, controlling some sort of motor, what-have-you.
  • The "cool" colours (blue, green, purple) I use for "input."  In practice, that means things like listening for the user to press a button, reading a sensor-value, what-have-you.

Again, that's personal preference.  But it's worked out pretty well so far.  Especially when one of my creations stops working and I haven't looked at it in awhile.  Like every person with a full-time job, debugging my personal projects is done in one-/two-/maybe-three-if-I'm-lucky-hour bursts.  Colour-coding in the here-and-now is a priceless gift from Present Me fiddling on a weekend to Future Me trying to get something up and running before bedtime on a weeknight.  'Nuff said.

Okay, assuming that you're done with prototyping and ready to put your invention into real-world use, AWG-based wiring, by laying flush with the breadboard, is far, far less likely than even a short jumper-wire to be accidentally pulled out where it could become a menace. 

Solid-core American Wire Gauge (AWG) wire:  Again, first things first.  AWG22 wire is your no-brainer breadboarding go-to.  In a pinch, you can probably get away with AWG20 (which, incidentally, is thicker than AWG22, not thinner).  There will be more wear & tear on your breadboard, but if that's all you can find down at the local hardware or auto parts store, it will get you through until you can order 22-gauge. 

Whatever else you do, give the pre-formed wire-kits a big ol' pass. #DoAsISayNotAsIDid  The reason being is that pre-formed wire is colour-coded by length, not function.  We'll deal with why that's a problem in just a bit.

Now.  The thing with AWG wire (of any gauge) right off the roll is that you will need an extra tool -- more likely two tools -- to work with it.  First and foremost is a wire-stripper to separate the insulating plastic from the conductive metal.   Any self-respecting wire-stripper will come with a variety of notches (corresponding to different gauges) plus a wire-cutter built in at the rear of its "jaw."

Because you're already expecting to work in AWG22, my strong recommendation is to permanently mark the 22 "notch."  Grab a tooth-pick and break out (or borrow) a bottle of nail-polish.  Bright red, hot pink, baby-blue, glitter-gold -- whatever will stand out against the dull black or maybe dull silver of the jaws.  Dunk ~1cm-worth of toothpick into the nail-polish and use it as a pen to draw a stripe parallel with the "22" groove on all four sides of the notch.  Then there should never be any ambiguity about which notch you're using to strip the wire.  Because when your wire-stripper includes finer gauges (e.g. AWG24, AWG26, etc.), "ambiguity" can mean that you cut your wire where you meant to strip it.  Ask me how I know.  :~/

When you're cutting wires for breadboarding, you will probably also want basic needle-nose pliers to bend the wire at right angles.  Yes, you might be able to skip the pliers and do this with your fingers.  Assuming that you're, um, blessed with something like the ten scrawny won't-last-a-day-after-The-Apocalypse twigs that my DNA gave me.  And even I prefer the precision of pliers  Pony up a few bucks at Home Hardware and call it a day, already.

Cutting wires for breadboarding has a learning-curve (albeit shallow).  But because I hate waste as much as I love you, I'll try to save everyone a few cm of wasted wire and go over my technique here in a "FWIW" spirit:

  1. With the wire-stripper, strip just under 1cm of coating from the free end of the wire.  My go-to technique is to grab onto the wire where I want to cut the plastic and twist the cutting edge of the notch around the wire core to ensure I cut through all the coating. 
  2. Insert the stripped ~1cm of wire into the "From" breadboard tie-point/pin.
  3. Bend the wire at a 90-degree to lie flush with the breadboard. 
  4. Stretch the wire to the "To" breadboard tie-point.
  5. Bend the wire at a 90-degree angle north of the breadboard -- i.e. the loose end of the wire should point up.
  6. Clip the free end of the wire ~1cm above the surface of the breadboard.
  7. Temporarily remove the "From" end of the wire from the breadboard to make the wire easier to finish off.
  8. Strip the coating off the "To" end of the wire from about half-way into the curve.
  9. Using your needle-nose pliers, bend the newly-stripped wire 180 degrees.
  10. Insert both ends of the wire into the breadboard tie-points.

(Bee-tee-dubs?  The same colour-coding principles as flexible wires apply.)

Once you have cut, stripped, and formed AWG jumper-wire, it tends to be less reusable than the flexible wires used for prototyping.  So until you develop an instinct for breadboard layout, you can save yourself a bunch of scrap by virtually breadboarding your project.  I talked about a couple of options (Tinkercad and Fritzing) toward the end of the "Breadboards" installment.  If you haven't checked them out yet, please do.

Next time, I want to talk about options for powering breadboarded projects.  Until then:  Tchein ton siault d'beluets!