Tag Archives: python

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.

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.

A Little Counter Intelligence

So I’m printing out a couple sets of Magic: The Gathering +1/-1 counters for an Etsy customer and I run into a problem. The red ABS +1/+1 counters are printing fine, but the -1/-1 black PLA counters are getting all feshnicket about midway up the print.

feshnicket couner

Good enough for a pickup game at Casa de Zheng, but one of these might show up at a tournament somewhere and we can’t have our customers looking anything less than their best.

If you don’t have your own 3D printer, you can get these counters on Shapeways, and if you do have your own printer head over to The Forge and print them at home. They’re in the Miniatures section.

These fellas are pretty small, so the newly-extruded PLA isn’t cooling off before the extruder head comes around to the same X-Y position on the next layer. Gooey plastic gets smudged a little bit and the edge of the counter becomes irregular. Fugly.

The solution is a little bit of custom gCode. A brief pause between layers gives the PLA time to stiffen before the extruder drags itself over the same spot.

The gCode needed for this is G4, or “dwell,” with a parameter measured in milliseconds. You’ll also want to move the extruder head out of the way while it dwells so that it doesn’t continue pumping heat into the print.

Here’s the gCode that needs to be added after each layer. Everything in parentheses is a comment and might make your interpreter go to la-la land.

G91 (set to RELATIVE positioning)
G1 Y10 F3900.0 (move 10mm in Y)
G4 P5000 (wait for 5 seconds)
G1 Y-10 F3900.0 (move -10mm in Y)
G90 (reset ABSOLUTE positioning)

You could add this with a Find/Replace in a text editor; just search for (</layer>) and append the gCode above to the end.

OSX’s TextEdit will actually let you add carriage returns to your find/replace fields if you hit CTRL-Q and then hit the return key. But saving that output gave me some weird text encoding errors, demanding that I switch from UTF-8 and it’s not 1994 anymore so WTF Apple.

It’d take me longer to figure out that text-encoding problem than it would to write a short Python script to do the job. Assuming you’re on a Mac and have in_file.gcode on your Desktop:

import os

# read the input file
f=open(‘/Users/zheng3/Desktop/in_file.gcode’, ‘r’)
#Windows and Linux paths are left as an exercise for the reader.
content=f.readlines()
f.close

gCode=’G91\nG1 Y10 F3900.0\nG4 P5000\nG1 Y-10 F3900.0\nG90\n’
# the \n puts a carriage return after each line.

for i in range(len(content)):

if ‘()’ in content[i]:
content[i]=content[i]+gCode

#write the output file
f=open(‘/Users/zheng3/Desktop/out_file.gcode’,’w’)
f.write(“”.join(content))
f.close

Then fire up out_file.gcode in ReplicatorG and a few minutes later, you’ve got yourself a decent print. Nice print on the left, yeechy print on the right.

fixed

Printrbot Simple: First Impressions


Lao Zheng's Printrbot Simple

In mid-May I got all hopped up on endorphins from 6AM yoga and BAM! right there in my Twitter feed was an offer. The first N users who bought a Printrbot Simple would save $50 off the already low, low price of $300. My impulse control weakened by the flush of healthy qi, I had one in my shopping cart within two minutes, or roughly the time it takes me to huff and puff four sun salutations.

Two-fiddy plus shipping isn’t a budget breaker for a 3d printed squirrel magnate, and the gnomes at Interdimensional Bank of Zheng say we haven’t skimmed anything off the upgrades fund in a while, so why not, indeed.

A quick note for anyone thinking they might purchase this printer once it’s out of beta in June and available to folks other than the lucky N.

if (eval(‘yourTime’)>=eval(‘yourMoney’)):
     buyADifferent3DPrinter()
else:
     thisIsThePrinterForYou()


If you’re a high school student with a few hundred bucks and a weekend to burn, grabbing the Printrbot Simple is a no-brainer. If you own a complete set of matching stemware, look elsewhere for your first 3D printer. Especially if your only exposure to 3D printing so far has been the SkyMall catalog.

Make no mistake, even more so than the Replicator1, this is a hacker’s 3D printer. You’re like two steps up from a homebrew RepRap when you get into the Printrbot Simple. If tweaking and calibration and watching prints fail while you dial in gCode ain’t your thing, purchase a different printer.

On the other hand: right after I made my first successful print on the Simple I was mobbed by Brazilian bikini models. Your mileage may vary.

On the gripping hand: as an instructional tool, the impact of the Printrbot Simple can’t be overstated. Anyone who assembles, calibrates, and prints with this bot is going to learn buckets about the ins and outs of 3D printing at a granular level.

Best of all, at $299, it’s relatively inexpensive. I’d be disappointed if hundreds of these bots don’t find their way into high school STEM clubs.

Well-to-do techie parents looking to build a 3D printer with their tweens might be the sweet spot for this bot, but Mom or Dad should be prepared to sneak back to the basement after bedtime to put in an hour or two of extra build time.

The Build

warning The Simple is a beta, so there are guaranteed to be some bumps along the road. It ships as a kit, so you’ve got to put it together yourself. You’re also paying someone else for the privilege of beta testing their hardware, which is a genius business model if ever there was one. Fortunately Printrbot is up front about that fact; “BETA” is laser-etched onto the build platform. You buys your ticket, you takes your chances.

Printrbot describes the build difficulty as “moderate.”

I am reminded of the time I went to the Thai place across town that isn’t my usual Thai place and I ordered the larb with a 7 on the 1 to 10 spicy scale which is where I like it but they use a different hotness scale and hoo doggies that’ll burn tomorrow on the way out but I could still mostly finish it. Ach, mein ass.

So maybe Printrbot’s definition of moderate is different than mine.

I’m not a complete idiot. I can read English and make logical deductions, I’ve got a well-stocked toolbox, I have an amateur’s burgeoning knowledge of electronics, and I’m not afraid to jimmy-jim-jim a part to get it to work. Surprisingly, given my pyrotechnic proclivities as a pup, I still have all ten fingers. I have a SparkFun wish list, for the love of Pete.

Even with my bona fides, I still find Printrbot’s estimate of one to two hours for assembly of the Printrbot Simple wildly optimistic. I’m sure there are wizards from the Printrbot community who can wham-bam-thank-you-ma’am this printer into a finished state in that time, but coming at this build cold I’ve probably got 8 hours put in over the course of three days. Keep build time in mind while you’re salivating over that $300 price tag.

Printrbot’s marketing claims that you can put this together with only a screwdriver. Maybe, if you’re the Last Son of Krypton or you have vise grips for hands. There are a few tools that will make this process much easier:

  • you’ll need super glue.
  • it amazes me that my kit didn’t include an Allen wrench. Maybe Printrbot figures that IKEA has acheived such market penetration that the probability of an Allen wrench being within reach is approaching 1.0 for a given location in the Western hemisphere.
  • a cordless drill with an Allen bit will speed up the assembly considerably.
  • a metric/Imperial ruler so you can tell the different bolts and screws apart
  • scissors or a hobby knife– you’ll be cutting fishing line.
  • an adjustable wrench, and maybe an M3 socket.
  • needlenose pliers
  • zip ties. You’re going to need a lot more zip ties than are included with the beta to manage all those cables.
  • painters’ tape for the print bed. No sense in marring that nice birch any more than you have to.

Most people willing to tackle this process are going to have this stuff in the toolbox anyway, I just include the list because I’m a huge fan of deflating marketing hype by emptoring my caveats.

There’s a point during assembly where one must gently fit two steel rods through laser cut plywood holes; these are the rods that stabilize the extruder arm as it traverses the lead screw. The holes are cut to very fine tolerances, so much so that it can be difficult to push the rods through.

I recommend that you put your steel rods in the freezer maybe an hour before you get started on the build. Thermal contraction will temporarily shrink them just enough to get them through the plywood. Once they warm up again they’ll be nice and snug.


rods in the freezer

Be prepared to slightly modify some of the parts that came with the kit to get them to fit. The laser cut plywood all fit together perfectly, but I had to file down the plastic edges of my hot end so that it fit into the extruder assembly. I accidentally stripped the wood around an M3 nut and had to super glue the nut in.

Not a big deal for your average maker geek, but someone expecting a snap-together 3D printer is going to be sorely disappointed around hour three. You can see where my file chewed up the top of the hot end in the closeup below.


hot end

Suggestions for Printrbot

I’d like Printrbot to etch more directions onto the wooden parts of the printer. Etched labels like “this side faces out” would be very helpful in determining orientation during the build. I got turned around a few times and ended up dismantling and reassembling the previous two steps of my build.

At the end of each step, a photo of the entire printer from multiple angles could help a lot. I kept getting disoriented and had to backtrack or skip ahead to find out what part went where.

Once you get the bot together the first print is very satisfying, but along the way there is likely to be some gnashing of teeth and rending of garments. Here’s a test print of a small cylinder that I did, just to make sure everything was put together properly.


first print

Calibrating the Printrbot Simple so that your prints are the right scale is a whole other can of worms. I’ll get into that in a subsequent post sometime in the next few days. Watch this space.

Timed Screen Capture on OSX

I’ve done a couple of 3d printing timelapses using a little application called Iris for OSX. Iris doesn’t seem to like to save my movies for some reason, but it at least gets the output from my fin de siècle webcam onto my laptop’s display so I can do something with it, like capture the screen once a minute and write it to a file using a Python script.

The Scrying Pool to the right uses a very similar process to take snapshots of the Forge while I’m working.

I’ve written this script to be as simple as possible for a novice who knows very little about programming. Being familiar with the concepts of variables and loops before using this will help, but really you should be able to paint-by-the-numbers and get one screengrab a minute without any extra work.

Bonus: some version of Python comes pre-installed on OSX, so you don’t have to install anything to get this to run.

To use:

  1. Make a new folder on your Desktop named capture
  2. Open TextEdit.
  3. Copy this script into a new text file. Save it on your Desktop with the name capture.py
  4. Open the Terminal.
  5. In the Terminal type python ~/Desktop/capture.py

That’s it! You can stop the script from running by hitting Control-Z in the Terminal.

# everything following a hash sign is a comment. Python doesn't execute comments. They only exist to make your code more readable.
# this script requires that you have a folder on your desktop called "capture"

import os,time

delay=60 # this number is measured in seconds.
i=0 # i is a common variable used for loops. We'll use this in the infinite loop later.
counter=0

while i<1:

# this is an infinite loop! we never change the variable i, so i is always less than 1.
# this script will run forever. You have to quit it with CTRL-Z.
# see how everything inside this while loop is indented by one tab?

# create a command that the Terminal will execute. screencapture is built into OSX.
# str(counter) turns the integer "counter" into a string so that it can be added to the command string.
# if you don't do this, Python will throw an error.
# the -x option turns off the screenshot noise.
# the -o option tells the OS where to save the captured image.
# ~/Desktop is the command line shortcut to your Desktop.
# this script will name the files capture.1.png, capture.2.png and overwrite those filenames in ~/Desktop/capture/

cmd='screencapture -x -o ~/Desktop/capture/capture.'+str(counter)+'.png'

# have the OS execute the command.
os.popen(cmd)

# let the user know what you're doing by writing the command to the Terminal.
print cmd

# increase the file number by one.
counter=counter+1

#wait a little bit. You've already defined delay up at the top of the script.
time.sleep(delay)

# this comment is outside of the while loop.
# if our code were to continue, it would start here.
My apologies for the meshuggeneh formatting on the Python code above. Can’t make it work without a CSS overhaul for the entire blog.

Announcing: The Forge

The Forge is now in live Beta at FORGE.ZHENG3.COM.

I’ve been eyeball-deep in HTML, CSS, Python, and WordPress for the last week, huffing and puffing as I try to wrangle The Forge into existence. There are going to be some bumps and bruises along the way, but I think I have a functional 3D model repository up and running. If you happen to find a rough spot, please email me or mention it in the comments. I’ll get some electric Bondo and gaffer tape on it ASAP.

I’ve got some fun plans for The Forge, but I’m also looking forward to a return to modeling my series of Magic: The Gathering tokens. Still got a whole mess of those to do. Stay tuned, freaks.