Category Archives: tinkering

Plutarch’s Debut is Nigh

workbench

Plutarch 1.0 is scheduled to make his party debut two days hence at J’s Halloween 2016 bash. The active duration of the party is roughly four hours. Here are my goals for Plutarch 1.0 during that time:

  • he must not fall off my shoulder
  • his head must remain attached to his body

Spontaneous decapitation has been a serious issue for this bird. His good-enough-for-prototyping attachment system might not be ready for primetime. We’ll see.

Whether his electronics work for the frightful fiesta’s duration is almost secondary.

While I celebrate the success of Plutarch 1.0’s ahead of schedule completion, I’m excited to get his successor out of the prototyping stage.

Here’s what Plutarch 2.0 looks like as of Halloween 2016. Keep in mind his deadline is 368 days in the future:

p2point0

He’s a discombobulated mess. But he’s much improved over his predecessor:

  • got 3D printed bevel gears working
  • added avoicebox with categorized, individually addressable sound calls
  • wrote a Maya-to-Arduino animation translator for the jaw movement
  • wrote a file processor that handles the WTV020SD-16P’s wonky-ass file format
  • amplified Plutarch’s speaker so he can be heard over party din
  • made a 3D printed chassis that’s modular and easy to assemble/disassemble
  • added multiple microphone inputs so that he can turn toward the loudest sound in the room
  • replaced soldered joints with connectors

Plutarch’s jaw opens and closes in sync with his sound calls. He’s got reliable, if shaky, 3-axis head movement. All of these systems mostly work, at least in isolation.

I just have to put everything together into a single, functional organism, at which point I can start working on the final challenge: his animation decision trees. Plutarch 2.0’s almost there and I’ve learned a tremendous amount about electronics and robotics over the last few months.

Unfortunately, I’ve just run into a couple of walls.

too many wires

Too many wires. Not enough space inside the body cavity for Plutarch’s y-axis servo to rotate freely. Voltage mismatch between the Pro Trinket and the voicebox and no room to cram a regulator in there.

Working in this cramped space is difficult (especially with a splinted pinky), and the microcontroller’s going to have to move to a more accessible spot. The 90° connections between Plutarch’s control wires and the microcontroller are eating up way too much servo rotation room.

Complexity could be conserved by tying a couple of grounds together. Connections could be used with higher-gauge wire. Options exist, but we’re gonna need a hogshead of brain juice over the next few weeks to figure all this out. And cash. Cold, hard cash.

It pains me to buy a $13 part to fix a problem I might have forseen but when one considers that $13 is an average morning at Starbucks for some folks, the bad feels wither away. Also I take comfort in the fact that I really have no idea what I’m doing so expectations really shouldn’t be that high in the first place.

A year remains before Plutarch 2.0’s unveiling. Still much to learn.

Internet of Stranger Things

TLDR; I made a Stranger Things Christmas Lights wall that you can control by adding #InternetOfStrangerThings to a tweet. It’s outside my house right now, blinking. Go ahead, tweet to it.

justice

Halloween! That time of year when Makers, who, if we’re being honest, are a little odd to begin with, let their freak flags fly with electronic projects of every kind. If you’ve been keeping up with the Zhengs you’ll already know about Plutarch the pirate parrot and the Lovely and Talented Mrs. Zheng3’s Arduino-enabled Pirate Pendant, but we’ve got one more project in the hopper this season: a Christmas light wall inspired by runaway Netflix hit Stranger Things. Plus, you– yes, YOU can tweet to this wall and your tweet will appear as a eerie sequence of glowing Christmas lights outside my house.

Try it yourself! Be nice, you bastids.

Let There Be Lights

Head out into the wilds of Amazon Prime and you’ll find plenty of LED Christmas lights that might– and we must stress might— fit the requirements of this project. Point against: our crack research team was dismayed to find that most modern Christmas lights seem to be spaced between 4″ and 6″ apart, which simply will not do for an application where the letters are more widely distributed.

Also, it’s highly unlikely that your garden variety Sunday church picnic Christmas lights are individually addressable. So in theeeeeeory we could buy a roll of Christmas lights, hack them apart with a Dremel and wire cutters and hope they’re what we need, or we could just make our own. DIY is ultimately more satisfying, so to the 3D printer it is!

Filabot was kind enough to send me a free roll of PETG+ for review. This filament prints somewhere between clear and frosty white, depending on the thickness of the model’s outer walls. It’s easy enough to whip up a few dozen hollow Christmas lights bulbs in Maya. (Got access to a 3D printer? You can download these models fo’ free at the The Forge.)

bulb

We don’t need the durability or transparency of PETG for the Christmas light bases, so they’re printed in MeltInk PLA/PHA and spray-painted black. These bases screw into the bulbs and have enough empty space in the bottom to accommodate a cut-down female header for plugging and unplugging.

Organization is key to completing a project with so many little parts! There’s not a lot of space on them for labeling with proper digits, so I hashmarked each base with silver Sharpie. This will help keep the colors in the proper sequence when I string up the lights.

sockets

Recovering from Failure

Strap in, muggles. It’s going to get technical for about a few paragraphs here.

Around Christmastime last year I was working on a project where I was trying to read data from 60-odd sensors. This project ultimately cratered, and we shall refer to it in hushed tones as the Multiplexer Incident of Winter 2015. It’s mostly behind us now. Mostly.

On the plus side, I learned an awful lot about multiplexers and cabling and bought a slew of electronics and more hookup wire than I’ll ever use. We can apply those newly-gotten smarts and parts to the Stranger Things wall.

First off, for those uninitiated– WTF is a multiplexer? In this context, a multiplexer (or mux, if ye be in the know) is a doodad that reads many signals into a single channel, or distributes one signal to many destinations. This wonderfully-written post at bildr will tell you how to read from this Sparkfun mux breakout, and writing to the mux requires only a couple of small modifications to the code. We’ll be writing to this mux to light up LED’s in a specific sequence.

Of course you need a bunch of colored LED’s, also.

You don’t want to run an LED without a current limiting resistor– down that path lies a wastebasket of fried electronics. Each mux can handle up to 9 volts, but that’ll cook the LED’s right quick. Happily these colored LEDs can be handily divided up into two groups; those with an operating range of 2.0-2.2V, and those that run at 3.2-3.4V. I put one 186-ohm on the SIG pin feeding the 2.2V LED’s and a 119-ohm on the other mux running the 3.2’s.

I told you it was going to get technical for a few paragraphs.

We want these LED’s to be in a predictable Christmas-light-like order: red, green, blue, orange, pink, purple, yellow, repeat, so there’s some software mapping of mux-pin-to-LED happening in the Arduino code. Higher voltage LEDs are on the mux labelled B.

light map

Building A Wall, Except Mexico Didn’t Pay for It, I Did

The budget for this project works out to less than $100, including plywood but assuming you’ve already got a 3D printer in the basement and your time has no value.

Programming microcontrollers, navigating the Twitter API, and tying it all together with heat shrink and hope is easy. Building stable outdoor displays out of 2×4’s and plywood? That’s hard, man. Definitely out of my element here, especially since I don’t have an easy way to make miter cuts in 2×4’s.

Confession: during construction, a piece of plywood fell down and hit me in the neck.

With enough screws and construction adhesive the whole thing should hold together for a couple of weeks and hopefully not fall over onto any pint-sized stormtroopers. Here’s the finished product– hat tip to our local Sherwin Williams for the Coriander Powder color match of a laser-printed Stranger Things screenshot.

daylight

Plywood ships in a 2:1 aspect ratio, but somebody really should manufacture 16:9 sheets for those of us who occasionally cross discliplines.

The “wires” strung between the Christmas lights are black nylon rope; the actual wiring is done with hookup wire stapled to the back of the wall. I also added “@” and “#” and @Zheng3_jim to the original A-Z. (You should probably follow me on Twitter if you’re not doing so already, cause I tweet about cool Maker shizz ALL THE TIME.)

This dog’s breakfast of electronics parts are jammed into a (hopefully) waterproof Ziploc storage container attached to the back of the wall. It’s a mess back there with the breadboards and jumper wires, but should be good enough for a temporary installation. Note warning label on it to discourage tampering and/or theft.

picovolts

Sun Tzu says: appear weak when you are strong, and strong when you are weak.

Reading From Twitter

Oy. A detailed description of how to do this is beyond the scope of this post. Suffice it to say that I’m using Tweepy, OAuth, and a poorly-written Python script that you can download here. Be sure to swap out my placeholder authorization tokens with your own.

In pseudocode, here’s how this whole thing works:

loop:

read the latest 100 #InternetOfStrangerThings tweets from Twitter
pick a random tweet from the list
filter the results for harsh language
if no appropriate tweet is found, use something benign (HAPPY HALLOWEEN, JUSTICEFORBARB, etc.)
smoosh the tweet into ASCII code

loop:

send the ASCII over serial to the Arduino as bytes
map the incoming byte to a mux pin
light the appropriate LED
wait a little bit between letters

wait a little while between tweets

Presumably one of the chans or reddit will eventually catch wind of this project, so before we send any text to the Arduino it gets filtered against a text file of slurs and epithets I keep around for precisely this purpose. There are kids around, for fuck’s sake.

An old laptop sits inside, shoving sanitized data into the Arduino through a 30-foot USB cable. That’s right, the tweets are coming from INSIDE THE HOUSE.

Download the microcontroller code here for a sterling example of how not to program an Arduino.

Tweet anything you like with the hashtag #InternetOfStrangerThings and it’ll wind up on the wall if your text gets past the filters. I’ll be tweaking the code between now and Halloween to make it more responsive to input from Twitter, and if I can figure out an easy way to set up realtime video stream I’ll do that too.

Happy Halloween if I don’t talk to you sooner. Lao Zheng out.

Arduino Audio with the WTV020SD-16P

There are plenty of ways to play sound on an Arduino– at the most basic you might burp out some bleeps and bloops with the tone() command, or perhaps drop some coin at Adafruit and get yourself a multifunction music shield.

Our current passion project at Zheng Labs is an audio-enabling upgrade to Plutarch the Pirate Parrot. For this application neither of the above options will quite fit the bill. We want a board that’s inexpensive, light, and small enough to fit inside a roaster chicken’s body cavity while leaving room for a battery pack, microcontroller, and an ever-increasing number of servos.

Enter The WTV020SD-16P. ‘Tis a picky, tricksy little board, but once you get it up and running it’s scrum-diddly-fun to use.

rex

#RAWR! you can download Rex for 3D printing over at the Forge.

To the tutorial!

GATHER YOUR PARTS

  • a WTV020SD-16P
  • a SanDisk 1GB MicroSD card: apparently the WTV020SD-16P can be a little picky about which brand and capacity of MicroSD card will work.
  • a speaker: This one comes with micro-JST connectors, which you can just snip off and plug into your breadboard. I soldered some jumper wires onto mine to make working with the breadboard easier.
    some jumper wires

And of course an Arduino and a breadboard. I dusted off an ancient Duemilanove for this project, but I’d imagine any Arduino will do.

GET THE SOFTWARE

You can get the sample code and the software library you’ll need at the Arduino forum.

Oh God. Forums.

I can’t be the only one who dreads wading into technical forums seeking assistance. In my experience one can find tiny nuggets of precious content only by softing through the dross, dregs and slag of misinformation, know-it-all-ism, and half-baked do-my-homework-for-me questions IN ALL CAPS from engineering undergrads in Gdansk.

Every now and then a patient, knowledgable member with a willingness to shepherd a n00b through a confusing and contradictory information maelstrom will emerge, but more likely than not a cheeto-crusted basement dweller will snidely inform you that a B+ in Electrical Engineering 101 at Carnegie Mellon is a prerequisite for posing a question to your betters.

Thankfully, the Arduino forum’s friendlier than most, and it’s a decent place to start looking for information about the WTV020SD-16P. There’s still a lot to unpack and sort out before you get your board talking, though.

Once you’ve gotten the sample code from the forum you’ll no doubt come across this image in all its JPEG-compressed glory. It’s the second post on the forum. You can’t miss it.

schematic

I can’t stress this enough: do not use this image as your Virgil to guide you through this particular circle of Arduino Hell. There’s nothing inaccurate about it, but there’s too much information here for those who want to just plug this thing into an Arduino without having to first procure an EE degree, and some of it is misleading.

This schematic will get you a WTV020SD-16P that works in standalone mode with some pushbuttons, to be sure, but if all you want to do is control the board with Arduino code this wiring diagram is overkill. For one, the pins in this schematic don’t match the pins specified in the sample code right above it, which is one of those Things You Don’t Know You Don’t Know if you’re just starting out.

My edited schematic is a little simpler and balls-on accurate, I promise. Behold!

schematic simple

You’ll note that the sample code includes a declaration for a Busy pin. It’s used for asynchronous audio play but we’re keeping things simple and not using it in this tutorial. Also, you’ll see several pins on the WTV020SD-16P labeled as NC: they’re Not Connected to anything and can be safely ignored.

If reading schematics ain’t yo thang, here’s what it looks like IRL:

wiring

To recap:

  • Arduino 3V3 to pin 16 (top right of the board)
  • Arduino pin 2 to pin 1
  • Arduino pin 3 to pin 7
  • Arduino pin 4 to pin 10
  • Speaker + to pin 4 (usually this is the red wire)
  • Speaker – to pin 5 (usually the black wire)
  • Arduino GND to pin 8

ACQUIRE AUDIO:

You can download the commonly used sample .ad4 files here, or use mine which IMHO are better for diagnostics and have the added benefit of not dancing on the knife’s edge of fair use and international copyright law violation.

If you’re visiting the blog from abroad you also can use my files to learn what a nondescript northeastern American accent sounds like. No charge.

Unzip the archive and drop the files into the root directory of your FAT16-formatted MicroSD card. Files must be named 0000.ad4, 0001.ad4, 0002.ad4, etc. The WTV020SD-16P supports up to 512 audio files, which should be enough for all but the most loquacious of parrot puppets.

Creating your own .AD4 files from WAV or MP3 of AIFF is brain-dead easy with this OSX tool, but you’ll need to install the JDK first.

Be sure to have your source audio sampling rate set at 32kHz or the software won’t produce any output and (not helpfully) any error messages indicating that there’s a problem.

SOFTWARE:

On OSX, drag the library folder into ~/Documents/Arduino/libraries/

The sample code on the forum shows off everything the library can do, but it’s too much for a proof of concept and has some English errors that introduce ambiguity in the comments. Let’s do some minor surgery.

  1. Cut out everything in between the curly brackets of the loop() function.
  2. Paste the following between the now-empty curly brackets after loop():
int r=random(0,6);
wtv020sd16p.playVoice(r);
delay(1000);

Power up your Arduino, upload the new code and you should be good to go. Good luck, and please post in the comments if I screwed anything up in the tutorial.

Watch this space for news on Plutarch 2.0’s evolution over the next few months. He’s scheduled to debut on Halloween 2017. You might consider watching his progress on Instagram or Twitter: that’s where the microupdates get posted first.

Lao Zheng out.

There Once Was a Project ’bout Venus

full

Longtime readers of this blog– both of them– know that here at Zheng Labs we’ve got a couple of rugrats running around the place. The older one’s in high school now, and has a practiced eye roll that earns perfect 10’s even from the Romanian judges. She’s not the subject of this post, although you can see photos of her pupal stage here and here, and some free 3D printable models to boot.

No, my friends, this week we bring to you the chronicle of my younger spawn and his adventures at the elementary school science fair. Each year his school puts on an open house for prospective families where they might explore for themselves the Hogwarts-like environment at one of Wisconsin’s fine public charter schools.

This open house features a gymnasium full of the kids’ long-term science projects, and is always a treat for those inclined to make things that go kablooie with papier maché, baking soda, and a little CH3COOH.

In years past procrastination and lack of interest have led my son to flail helplessly in front of a sloppy trifold when the time to present his project came, and this year we were determined not to repeat that particular learning experience. We got started early, enlisted a 3D printer, and won the science fair.*

*on “winning:” the event is actually noncompetitive and the school doesn’t give out prizes. I’ll define winning as spending a couple hours in the basement with my son, teaching him how motors and voltage and switches and soldering irons and burn creams work. Plus the look of unadulterated joy on Xiao Zheng’s face when the project worked: priceless. Scroll down to the bottom of the post for the big payoff video.

Also, the kid who actually won the science fair was the one with the trifold cheerfully labeled “Exploring Uranus.” That kid’s going places and has either fantastic or clueless parents.

Astute readers may have surmised that this year’s theme was space science, and the thrumming gymnasium was packed, absolutely packed with elementary school children wearing astronomy-related costumes. One kid was a dead ringer for Carl Sagan (red turtleneck included). Galileo and Halley’s comet were easily identifable from across the room. One young man made a fantastic Pathfinder rover hand puppet, a young lady was fetchingly dressed as the day and night cycle complete with helium balloons tied to her pigtails, and much aluminium foil was spent in the pursuit of knowledge.

Soviet science was well represented, too. The neighbor kid dressed up as Sputnik, and there was even a kid in full bright-orange Yuri Gagarin drag. Imaging getting that costume past the a 1950’s school board here in Appleton, Wisconsin, hometown of national disgrace and Ted Cruz lookandthinkandsoundalike Senator Joe McCarthy.

McCarthy’s grave is right down the street, should you feel the need to urinate.

I’d post photos of the science fair, but! Kids’ privacy issues. You know the drill. Local parents: if you’d like to share a photo of your kid’s costume, send it my way.

好久以前, back when Zheng himself was xiao, Dad and I spent many evenings in our basement laboring on school projects. In all fairness it’s safer to say that Dad did the heavy lifting and I just provided parameters, but man those projects were the envy of the other kids in elementary and middle school. I wish I had photos of the tornado diorama, or the sculpture of Zeus made of toilet paper, shellac, and Ivory soap flakes (!) or that Roman aqueduct we (Dad) made out of grout and PVC. Or the paper bag mountains with joint compound glaciers. Or the passive solar house model made out of foamboard reclaimed from the dumpster at work.

Thanks Dad, for doing those projects with me. I’m doing my best to pass your creativity down to your grandkids. Cir-cle of liiiiiiiiiiiiiiiife!

But I digress. This is a 3D printing blog first and foremost, and you’re here to read about the process of creation.

We got the trifold part of the project out of the way first, and settled into working on the costume part of the presentation. Our challenge: making a wearable model of Venus. Xiao Zheng’s first idea was to hand-letter the word “VENUS” on a piece of cardboard and hang it around his neck. He’s literal that way sometimes.

A planet-like sandwich board was also considered and quickly discarded as “stupid” and uncomfortable to boot. We gnashed teeth and rended garments for a while before remembering that his bike helmet has a GoPro mount on it, and would be a perfect platform on which to place a model.

The model of Venus itself is nothing fancy, just a lightweight ball of bubble wrap shrouded in painted tissue paper. It masses approximately 116 grams. The actual planet Venus masses 4.867 × 1027 grams.

venus

I introduced my son to the joy of inadvertently huffing spray paint fumes in the garage, which he liked. Maybe too much.

huff

Just attaching Venus to a helmet’s really not enough when the other kids are dressed up as Saturn V rockets, so we had to take it to the next level by making the model spin. I’ve got a bunch of old DC motors kicking around because of course I do, but we quickly realized that even if we could attach the motor’s axle directly to the model, it’d spin way too quickly.

We needed to slow the spin and the solution, as it is to so many things, is gears. Fortunately, I’ve already got some at the ready.

So a few minutes’ modification in Maya and we’re off and printing. Pro tip: gaffer tape works astonishingly well as a print surface for ColorFabb’s PLA/PHA. Note that there’s a cup integrated into the top of this gear to give the planet more surface area for adhesives.

gear

Next we’ve got to get the gears onto the helmet, and fortunately there’s a GoPro-compatible mounting system in the Forge. A few more minutes of vertex wrangling and a couple of test prints and the mounting system looks like so:

assembled

(You can download the models here if you’d like to take a peek at them.)

The rotation is controlled with a momentary switch hidden in the kid’s pocket. Hold the button down and Venus spins faster and faster. Of course, my kid’s teachers aren’t pants-wetting bigots and he’s white as Wisconsin snow and not named Ahmed, so nobody batted an eyelash at this suicide-bomber-looking pushbutton setup. It’s even RED.

switch

Fun fact: Venus’ day is 243 earth days long. I learned this from the aforementioned girl dressed as the day-night cycle.

Everything’s gaffer-taped together to insulate the solder joints and the wires are hidden under clothing.

The project survived the entire night on one set of 4 AA batteries and finally met its demise when my son, in an all-too-typical display of spazzy exuberance, head-butted the kid dressed up as a Soyuz capsule during cleanup and Venus went spinning across the gym floor and into the hallway.

Lao Zheng out. Thanks again, Dad, for teaching me how to do a science fair project right.

The Agony of The Feet

plutarch on rail

If, bit by bit, you replace the parts of a store-bought pirate parrot with 3D printed components and electronics, is it still the same parrot in five years?

Another Halloween has come and gone, and no, I did not festoon the house with an Arduino-controlled lightshow as I had planned to do in July.

Nor did I design and print that glowing Riddler sword cane I’ve been wanting to get to, and I also failed to make any headway on that EL wire and fog-machine witches’ cauldron I was so pumped up about two years ago.

What I did manage to do was stay married to the lovely and talented Mrs. Zheng3, who in addition to being lovely and talented also had the foresight to order us up a couple of relatively inexpensive pirate costumes from some online retailer.

See, here’s the thing about Halloween costumes. A store-bought costume is all well and good, but I gots ideas, man. Next time you and I are having a beer ask me about my plans for a two-person piñata donkey costume. If you whack us with a stick we’ll drop a bunch of candy out through a trapdoor in the belly. It’s-a-gonna-be-awesome.

pinata

Of course, I don’t have the time to make this. I also must make peace with the idea that I will never, ever, learn how to do DIY vacuum forming and craft myself a suit of Dr. Doom armor. The probability of my constructing an animatronic tarantula the size of a Great Dane approaches zero. Halloween’s an annual exercise in abandoning fun projects before they get started.

But you’ve gotta have a costume, right? Especially since we annually attend a spectacular haunted house/halloween party thrown by good friends of ours out in the boondocks of Hortonville, Wisconsin. Can’t show up there wearing my usual costume of cargo pants and free trade show T-shirts.

As she’s done so many times in the past, the lovely and talented Mrs. Zheng3 pulled my bacon out of the fire with an assist from Amazon prime and MasterCard, and now we’ve got pirate gear aplenty.

But what about next year? And the year after that? We’ve decided that our best option is to commit to the pirate life completely and upgrade our costumes by degrees. This year’s our baseline, and at some point in the next twelve months I’ll buy a nice set of leather boots to replace the cheap vinyl boot-tops that go over my dress shoes.

(The costume has a little tag on the inside that says, I kid you not, DO NOT WASH. Need to replace the shirt ASAP.)

do not wash

Maybe next year I’ll find a flouncy pirate shirt that can do double duty at the renaissance faire. And the year after that I can fall off my wallet and get a nice steel cutlass. And so on and so forth and in five years I’ll have a really great pirate costume just hanging in the closet.

We also bought a polystyrene parrot accessory. He doesn’t look too bad for $10 but the UX could use some love. At the most basic level, it’d be nice if I didn’t have to worry about my bird falling off to join the choir invisible every time I reach for the guacamole.

Plutarch’s original feet have two problems. First, they look nothing like actual parrot feet. Parrot feet are weird, and these are clearly sparrow feet repurposed by an overworked factory manager in Guangzhou.

original feet

Second, the feet don’t ship with a convenient way to attach to the wearer. Plutarch ships with a shoelace-like strap that’s halfheartedly hot-glued to his sole, intended to loop under his owner’s armpit. You’ll see from the Amazon reviews that this is a less-than-optimal solution.

Magnets are my go-to solution for holding things together. A while ago I bought a passel of tiny neodymium magnets for some long-forgotten purpose, and I still have about fifty of them left. A few minutes tweaking a cube in Maya gets me a pair of parrot feet with little sockets for the magnets. The magnets are friction-fit, but being a belt-and-suspenders type of hominid I’ve super glued them in.

feet magnets

A steel tuna fish can lid, easily hand-bent to be convex, hides under my clothing. I’ve covered the lid in athletic tape because it’ll be under a white shirt eventually and I don’t want it to show through.

feet pauldron

Besides, I’m nursing a rotator cuff injury, again, and have no other use for my athletic tape for at least a month. Feh.

Also, Coco gives approximately 6.02×10-23 f_cks about this parrot.

These feet are printed flat in ColorFabb signal yellow PLA/PHA, which is easy enough to deform post-print with a little bit of heat. A few months ago I bought this great little heat gun for heat-shrink tubing and it does a fine job helping me mold Plutarch’s toes to my shoulder.

plutarch shoulder

In the long term I’d like to put some motor control into Plutarch’s head so that he can swivel to look at stuff. And a webcam. And a speaker. And wireless control so that I can control the parrot from across the room.

I’ve already got a wee servo on order from Adafruit, so that’ll be next weekend’s project.

Like I said, I gots ideas. Check back in a year and we’ll see how far I’ve gotten.

Why Plutarch? Ship of Theseus, grandfather’s axe, and all that.

Lao Zheng out.

All About That Base Are Belong To Us: Controlling an LED with an NPN Transistor

unforeseen problemFull disclosure: I have no idea what I’m doing. If you arrived here by googling CONTROL LED NPN TRANSISTER then you probably know only slightly less about electronics than I do.

Frankly I’m not real clear on exactly what voltage is. People keep telling me charge is like a swimming pool, and the voltage is how much water pressure you have, and the current is how much water flows out of the pool, and resistance is how big the pipe is that the water’s flowing out of, but honestly that makes no intuitive sense to me. No sense at all.

Apparently resistors have something to do with Buddhism because ohms? What. Evs.

I’m a huge fan of getting things working first and understanding them later, so let’s just barrel right ahead and be willing to break stuff for science. These components are relatively inexpensive, so even if you burn a few bucks you’ve gained some knowledge from the carnage.


Here’s what you’ll need:

parts

One. A power source. I’ve got an old 7.5V wall wart power adapter scavenged from what I’m guessing was a D-Link router at some point in the past. You can use any power source you like for this, just so long as you’re pushing somewhere around 5V. Four AA batteries will work great for this. Don’t get your power directly from the wall unless you’re seeking a new career as a fried ham.

The leads on this power supply are stranded wire, which doesn’t jam into breadboards very well. I’ve soldered them solid– not strictly necessary but helpful. If you do this yourself please don’t solder the leads while the power supply is plugged in. Is bad idea.

I’ve used blue painters’ tape to indicate the positive lead on this. Red’s the conventional color, but I ain’t got no red tape, son. Blue it is.

Two. An LED! You can buy these guys by the dozen for cheap, and some places will even sell you resistors in the package. I’m using a green LED. These tend to run somewhere around 3.3V (this matters, and you’ll see why in a moment.)

Any DIY project is improved by adding LED’s to it, so you really ought to have a few thousand of these at the ready. Making a Halloween costume? LED’s. Grade school diorama? LED’s. Bran muffins? LED’s, baby.

Three. Some resistors! Here’s why that 3.3V matters: remember that the power supply I’m using is 7.5 volts. Hook that puppy up to a dinky little 3.3V LED and kablooie– the LED will flash briefly and then die forever. The resistor’s going to limit the amount of juice flowing to the LED by turning excess electricity into heat and dissipating it into the air.

Trenchant insight alert: THIS IS WHY ELECTRONICS GET HOT WHEN YOU USE THEM.

I’m using a 12K and a 5.6K resistor for this project, which I picked at random from a pile of bent resistors in the bottom of my toolbox after a 100K resistor blocked too much current to light an LED.

Voltage calculations and predictions as to whether I will eventually burn up my components are left as an exercise for the reader. EE’s are free to leave helpful comments below.

Fo’. An NPN transistor! It’s tough to buy just one of these. Here’s a pack of one hundred, so you can screw up a bunch of times. We’re going to use one transistor as an electronic switch. What you do with the other 99 is up to you.

Five. A short length of hookup wire. Pretty much anything conductive will work for this– don’t worry about gauge as we’re not exactly building a space probe here. Use a paper clip if you’ve got nothing else.

Six. A solderless breadboard! (not pictured) You’ll probably want at least three of these in your house so that you can leave half-finished projects assembled while you attend to more pressing duties, but you only need one for this project.

The Basic LED Circuit

Let’s assume that you’ve never done this before. We’ll wire up a basic LED circuit to build confidence and then move on to adding the transistor.

Step 1: Connect the power to the breadboard. Plus to plus, minus to minus.

power hookup

Step 2: Connect the 12K resistor to the + strip and somewhere else on the breadboard. We’ll use a second resistor later when we want to avoid frying the transistor.

add resistor

Step 3: Connect the long lead of the LED to the free end of the 12K resistor.

add LED

Step 4: Connect the short lead of the LED back to ground with a piece of hookup wire.

LED circuit

And if all goes well, you should have glowing LED, with brightness dependent on your combination of resistor and power source.

So that’s LED’s 101. I still don’t know how this relates to swimming pools.

The Transistor Circuit

Let’s complicate things just a bit by adding the NPN transistor. Pro tip: It’s always helpful to remove all cats from the work area.

cat

Let’s not dwell on the difference between NPN and PNP transistors: there are plenty of other places on the internets to explain that, full of confusing diagrams and weird-ass equations. For morons at our level it’s enough to understand that when electricty touches the middle pin of an NPN transitor, current flows through the transistor. Otherwise, the transistor acts like a closed gate, and no electricity passes through it.

I’m using a 2N4401 transistor, but any NPN should work for this little tutorial.

Step 6: Take out the LED and hookup wire and insert the transistor so the curved side is facing away from you.

add transistor

Step 7: Connect the long lead of the LED to the rightmost leg of the transistor. Wire the transistor’s leg back to ground with your little piece of hookup wire. If you’re fortunate, nothing will happen.

wire to ground

The LED should still be dark, but if it’s glowing dimly then (I guess?) a little bit of current is passing through the transistor. You can use a more powerful resistor or lower your input voltage by swapping out your power supply.

Or just plow on ahead and don’t worry about incinerating your components. That’s what I’d do.

Step 8: This is where the magic happens! We’re going to apply current to the transistor’s middle leg, which will permit current to flow through the transistor and light up our LED.

transistor circuit

Just to be on the safe side I put my 5.6K resistor in between the source voltage and the transistor’s middle leg. Of course you could read the datasheet and know for sure how much voltage that middle leg can handle (spoiler: it’s 6V read Andy’s comments below) but reading datasheets is for suckers who didn’t buy a 100-pack of transistors.

This Circuit is Stupid

Yeah, I know. But it’s a proof of concept, right? Instead of keeping an LED lit (lame) one might be using this transistor with an Arduino digital pin wired to the middle leg. One could toggle massively interesting circuts by writing HIGH or LOW to the circuit from the Arduino.

Or, OR! In theeeeeeeeeeory, one could use this basic circuit to resolve conflicts among I2C devices with identical hardware addresses by interrupting the SCA signal, if one had accidentally purchased A TSSOP multiplexer and SOIC breakout boards and had a week to kill while the proper components were being shipped to his lab and needed to feel like he was making forward progress on some front for the love of Pete, because none of us are getting any younger, you know, and Time is the enemy.

I’m not saying that happened. But it could have. In theory.

#staytuned, my friends. Lao Zheng out.

Vacation Photos and RGB Sensors

So I’m back from a week travelling across the western half of Canada with the lovely and talented Mrs. Zheng3 and her parents. We now return you to your regular schedule of intermittent blog posts.

The trip began in Vancouver where I enjoyed the singular pleasure of spending a couple of hours meeting with the Pinshape team at their mothership. We discussed some of the more pressing questions facing 3D printing designers today, including but not limited to where one might obtain the best dim sum in BC’s fairest city.

Great bunch of folks, these Pinshapers. Sharp as tacks and friendly to boot. Take a look at their site and you’ll find a nicely-curated selection of models.

Robber Rex (a favorite at Pinshape) managed to visit the Vancouver Public Library, which has been cunningly constructed to resemble the Roman Colosseum.

vpl

hashtagRAWR.

The Saskatoon train station is as bleak an outpost as you’ll find, but still a welcome diversion for a constipated Parasaurolophus who never quite got the hang of pooping in a cramped train toilet.

saskatoon

The long train ride from Vancouver to Winnipeg, made longer by frequent sidesteppings to allow freight trains to pass, allows for much contemplation and idea generation and idle sketching upon napkins, and by the time I returned home I was more than ready to jump into the next project: RGB color sensing with Arduino.

There are, presumably, roll-your-own RGB sensors cobbled from disposable contact lenses, photoresistors, and Oreo cream, but at some point one must accept that expedience takes priority over molecular-level knowledge of a process and you just can’t be mining your own beryllium all the time. So to Adafruit we go, and earlier this week a TCS34725 RGB color sensor arrived on the doorstep of Zheng Labs.

milton inspecting

The Adafruit tutorial is remarkably easy to follow and we were up and running in less time than it took to print George Timmermans’ handy Arduino and half-sized breadboard caddy, including the time required to solder the sensor to some headers with long-unused and filthy soldering iron tips.

I’d link to the caddy directly except that WordPress is throwing some weird Unicode error and it’s too early in the morning to troubleshoot HTML errors. It’s on Thingiverse.

This little board contains a white LED that burns with the intensity of a thousand suns, so you may want to wire it to ground and turn it off while you’re experimentin’ or you’ll be seeing afterimages of your workspace for hours.

caddy

The book in the background is fellow Wisconsinite Jordan Ellenberg’s How Not To Be Wrong, which, 50 pages in, is so far a fun read. Any book that starts off with a humorous telling of statistical analysis of bullet holes in WWII airplane fuselages is going to be good.

Our engineering team ran into a little bit of trouble trying to get Unity3D to talk to the Arduino and settled for a temporary solution using Python code direcly cannibalized from 2012’s Etchasketchulator project:

import serial

ser = serial.Serial('/dev/tty.usbserial-A700fjTr', 9600)

def wait_for_arduino():

     while (true):      
          valueIn=ser.read(50) #read the first 50 characters that the arduino is sending
          print (valueIn)

wait_for_arduino()

That /dev/tty.usbserial-A700fjTr serial address is the currently free USB port on my MBP: if you’re using a PC you’ll likely replace that string with something that looks more like COM4. Check your Arduino IDE to see which port to use.

serial screenshot

Looks like I need to make the serial communication a little more elegant; it’s timing out, throwing errors, is badly formatted, and generally a mess. But let us not let the perfect be the enemy of the good. Iterate now, fix later.

ball pit

I used a couple of ball pit balls as test objects. In the interest of presenting properly-formatted data let’s go direct to the Arduino serial monitor for the output:

Offscreen I’m waving a red ball over the sensor and, wonder of wonders, the red values change over time.

arduino serial

Next step: communicating with a passel of these RGB sensors. This should be a challenge, since each one has an identical address and as far as I know they can’t be changed in hardware. Getting ready to hop on the I2C bus.

I’ll clean up the serial communication by next time, promise. And calibration. Gotta do some pre-read calibration of the sensors for ambient light levels, too.

Note to self: buy new soldering iron tips before we go down this road. #staytuned.