Archive for the ‘gEEk’ Category

Cubeternet 2MP UVC webcam teardown

August 25th, 2010

For my pick and place project, I picked up a pair of too-good-to-be-true webcams: the Cubeternet no-name UVC webcam. For this project, there is a lot to like: 2MP resolution (claimed, at least), built-in LED ring, cross-platform UVC interface, hand-adjustable focus and a legitimate glass (no polycarbonate) lens…for $16! Alas, my review of this cam is currently mixed, since one of the cameras failed after being plugged in for more than a few minutes. This particular camera – the first I tested – became warm to the touch soon after plugging in; I assumed this was normal operation and that the cam’s solid metal “eyeball” enclosure was the heatsink for a voltage regulator screwed into it. Turns out this is not normal at all; the 2nd camera does not get even slightly warm after running overnight. Now, what to do with a broken webcam? Take it apart!

Teardown photos: In here

Opening the case reveals solid components, but an unfortunately typical “Chinese toy” construction with hand-bent and soldered leads everywhere, a couple stray solder balls and liberal application of hot glue (yes, really) to hold everything in place. If you’ve ever taken apart a cheap electronic toy for soundbending, you probably know what I’m talking about. Of the identifiable ICs, there are:

Controller:
Vimicro
0342PL
TS0340B
(Integrated USB2.0 UVC camera controller in 44-pin TQFP; its manufacturer denotes it as VC0342. This is driven by a 12MHz crystal oscillator.)

EEPROM:
Turbo IC, Inc.
TU24C64CSF
29830628
(64-Kbit I2C EEPROM in SOIC-8. Probably contains imager-specific register initialization values; possibly vendor-specific data such as USB ID and descriptors / vendor strings.)

Voltage regulator:
Kingbor 6206A
0947/33
(Ho-hum, 3.3V 3-terminal regulator.)

Imager:
Typical “big glass plate” CMOS image sensor, but actual manufacturer/part is anybody’s guess without a good microscope.

Misc:
There are six very bright LEDs hand-soldered into the board and bent into position; an electret microphone is also glued into the case. A handful of what appear to be discrete transistors/FETs deliver power to the LEDs and may serve a purpose switching/sequencing power to the imager.

In the images of the controller side, you can see a big solder blob dangling precariously off one of the FETs onto the PCB. While it’s not clear if this one was the culprit, this blob or one of a couple similar ones are the most likely cause of failure. Despite all this, the lens assembly is all glass as claimed, and seems to be of much higher quality relative to the rest of the guts. The minimum focus distance is well below 1 inch. On another bright side (no pun intended), the LEDs are bright as hell, adjustable via an analog thumbwheel on the USB cable, and holes in the four corners of the square board can allow easy attachment to the placement head. The untimely death of one of the cameras is certainly discouraging, and given the internals can’t be cleanly written off as a fluke. Still, even assuming a 50% failure rate, doubling up on these cams is still a good bit cheaper than the nearest name-brand equivalent.

Tags: , , ,
Posted in gEEk | Comments (0)

Image segmentation for PnP optical placement

July 27th, 2010





Quick ‘n dirty (but working!) image segmenter for randomly-strewn part identification. About 1 page worth of scripting takes an image of objects on background, determines which part is the background, determines the outside contour of each object and numbers each as a separate object. Now that it’s known where to look for one specific object, the task of identifying that object (or just matching it to another just like it) becomes a whole lot simpler. Combined with the auto-aligner, this reduces a “naive” (bruteforce cross-correlation between needle and haystack images) image matcher to only having to scan against 4 orientations (90-degree rotations) to find which has Pin 1 in the right place (and whether it’s the same part, etc.) Hopefully as I dig deeper into opencv, there is a less-naive algorithm builtin for this that does not rely on contrast/color historgrams: most electronic parts basically consist of a flat black body and shiny reflective metal leads (i.e. appearing the same color as your light source and/or the background, and/or whatever happens to be nearby at the moment). Edge-based stuff still seems like a better approach, though I would welcome being proven wrong if it means not having to write the identifier from scratch myself :-)

Steps in brief:
The first image was taken using the actual webcam that will be attached to the pick n place head, looking at a handful of representative parts on a piece of white paper. This image was dumbly processed using a Sobel edge-detector (it’s builtin to Gimp and I was feeling lazy), Gaussian blur to expand the soon-to-be-resulting mask around the part a little and close any gaps in the edge-detection result, and finally threshold the result to produce the second image. The goal in these steps is to produce a closed-form contour blob for each part that’s at least as wide as the part, while minimizing stray blobs from random noise / dirt specs / etc. (internal, fully-enclosed blobs/noise due to part features/markings is OK). Finally, opencv’s FindContours function is run (mode=CV_RETR_EXTERNAL) on the resulting image, returning a vector that contains a polygonal approximation of each external contour found. Each discrete (non-touching) contour blob is returned separately, that is, every part in the frame is now effectively tagged and numbered!

There are a couple noise points identified in the image above. Better-chosen constants for the initial image operations (threshold, blur radius, …) may help, but I’ll probably end up having it measure the area of the blobs and throw away any that’s too small to possibly contain a valid part. Switching to a more advanced edge-detector, e.g. Canny, may help too. In any case, the full image matcher should figure it out eventually :-)

Code Demo – basically ripped straight from the pyopencv examples
Segmentation example – requires Python (2.6) and opencv 2.1.0 / pyopencv.

Tags:
Posted in General, gEEk | Comments (3)

Pick ‘n Place Head

July 26th, 2010

This weekend I got some parts in and put together a preliminary placement head for my open-source pick ‘n place project. My requirements are that it be buildable with off-the-shelf parts (ideally same-source, to save on shipping) and no special equipment, allow +/-180 degree rotation while maintaining an undisturbed vacuum, and support interchanging of the “tools” (vacuum needles). All that’s really needed to build this are the discrete parts shown, a bit of drillable plastic (e.g. Delrin) for the base material, and a drill. A drill press would be handy (a CNC mill *really* handy, and not such an out-there thing to have considering you are probably retrofitting this onto one).

This head consists of a hollow rotary shaft with a Luer lock fitting on one end, right-angle flexible tubing barb on the other end, and a large toothbelt (notched belt, timing belt) gear in between. The shaft is held in place but allowed to rotate by a pair of bearings, and the rotation is provided by a small stepper motor at the other end of the toothbelt. The gear ratio is approximately 5.2:1, providing a rotational resolution of about 0.35 degrees/step with a common 200 step/rev stepper motor (if no microstepping is used). Finally, just to the left of it is a 1024×768 Webcam with manually adjustable focus and a ring of built-in LEDs for lighting. The webcam mounting is definitely not ideal, given the camera’s weird eyeball-like shape. Tentative plan is to lash it down with some string, align it nicely with respect to the CNC table, then backfill the opening the camera’s butt sits in with epoxy.

The hardest part was finding a combination of parts that would all fit together nicely. Currently, the fits are mostly exact to “pretty damn good”, but a bit of adhesive is needed to join them permanently.

Parts List
Unless otherwise noted, all of these parts were sourced from Small Parts Inc. in the US due to the large selection and an actually competent parametric search engine, which was a great help in finding combinations of mutually-fittable parts. Accordingly, measures are in Imperial unless noted otherwise (that’s just how they come here).

Partnumber Desc.
3002DSTNTG18 Nice Ball Bearing 3002DS, .250″ bore x .6875″ OD x .250″ width
BFM-250-P Mounted sleeve bearing, .250″ ID, 1 17/32 center-to-center bolt spacing
B00137SITY Steel tubing, 1/4″ OD .152 ID, 12″ long
40DP-14/S-01 Timing Belt Pulley Delrin, 0.0816 Pitch, 40DP, .350″ Diameter, 1/8″ Bore, For up to 1/4″ Wide Belt, 14 teeth
40DP-70/S-01 Timing Belt Pulley Delrin, 0.0816 Pitch, 40DP, 1.806″ Diameter, 1/4″ Bore, For up to 1/4″ Wide Belt, 70 teeth
TB188-090-01 Timing Belt Urethane/Polyester, Single-Sided, 0.0816″ Pitch, 0.1875″ Wide x 7.3440″ Long, 90 Teeth
LCX-LC005 Male Luer Lock to tubing adapter, .145″ OD hose barb (mates well enough with .152″ ID steel tubing)
F1-EL001 Elbow Connector , Classic Barbs for 3/32″ ID Tubing, .145″ OD
HSTA-08-24-10 1.5″ aluminum standoffs, 8-32 thread
B00137UP68 (Optional) 11ga Steel Tubing, .120″OD, .094″ID (for mating 2mm shaft stepper motors, if used, to the 1/8″ pulley

Misc. Parts
2x 2″ x 4.5″, 1/4″ thick pieces of Delrin or similar
4x 1/2″, #4-40 bolts and nuts (assuming 2 bolts for stepper motor)
4x 1/2″, #8-32 bolts for standoffs
1x Webcam, manual focus, hi-res and builtin lighting strongly recommended
1x 3mm shaft stepper motor*
1x Method of attaching to your mill – a bit of aluminum angle bracket, or a dovetail, etc., depending on your mill.

* The timing pulleys and stepper motors only come in a handful of diameters (imperial for the pulleys and usually metric for the small motors), so a 3mm (.118″) motor onto a .125″ ID pulley was the closest I could come up with in a reasonable amount of effort. Any small, el-cheapo permanent magnet (“tin can”) stepper motor should work here, but sourcing it may be annoying. Off-the-shelf 3mm-shaft motors I found are Jameco’s ValuePro 42BY48H08, Anaheim Automation’s TSM42 series, and Portescap’s 42/44 series e.g. 42×048 and 42S100. This surplus stepper is also worth a look, but you’ll have to remove a pre-attached plastic(?) gearhead. Beware, many of these smaller motors are 7.5deg/step, so even with the gear reduction, you will probably want to look at microstepping them to ensure adequate rotational resolution. Also, most of the companies selling them have no online click-and-buy ordering; you’ll have to phone up a salesdouche at the least, hope that you are worth their time to buy One Lousy Motor, and possibly haggle (“Request a Quote”). How companies that don’t know what their product costs stay in business is beyond me, but that’s a rant for another day.

If you want to skip that hassle, I’ve taken an alternative approach and simply bodged a surplus 2mm-shaft motor up to a 3mm shaft by gluing a short piece of thicker steel tubing onto the existing shaft (see partlist).

Design Files
CamBam drawings with machining operations for the top and bottom plates. The machining ops assume 1/4″ thick plastic, 1/8″ endmill for most cuts, and .166″ (#19) drill for the #8-32 bolt holes into the standoffs. It’s designed for the Cubeternet webcam (or equivalent eyeball-cam) and a stepper motor with 42mm center-to-center mounting holes. You can get the free CamBam at http://www.cambam.co.uk/.

Note, I made some small improvements to these files after the above prototype was carved, so what you see in the file will not match it exactly. In particular, the standoffs were moved to more optimal places and a feature has been added allowing the motor to be slid to remove any slack in the belt.

Assembly
The assembly should be pretty obvious. One bearing on each of the Delrin plates (inset the ball bearing if you can; otherwise gluing it down should be fine). The hollow shaft goes thru the bearings, Luer adapter and hose barb go on either end (use adhesive, just don’t clog the air path with it). The motor shaft center should sit just a hair (50-100 mils?) over 1.75″ from the hollow shaft. On mine, an online calculator produced the 1.75 figure, but the belt turned out to be a bit loose once built this way. If possible, make an elongated hole for one of the motor screws so the motor position can be adjusted to tension the belt. You could probably also insert a peg somewhere in the belt path to push it inward and take up the slack. With the camera focus set such that the largest part you will ever populate can fit in-frame, find the resulting camera height (distance from part) and set the depth of the shaft so that the camera is “in focus” maybe an inch or two above the placement position (i.e. with the needle touching the board). This will allow the head to focus on parts without touching the needle down.

Suggested “v2″ improvements
–Move air valve (if/when one is specified) onto head to minimize air volume between valve and head. Needed? (may be beneficial for reversed aquarium pumps or other weak vacuum sources)
–Bump detect: rather than firmly adhere the shaft into the bearing, allow it to float up and down, normally resting by gravity with the large pulley against the ball bearing. Place a contact switch just above the pulley: if the head/part contacts the surface with more than minimal force (enough to lift the shaft), contact switch is triggered. This could be used to halt the machine if a bump was not expected. If the switch’s trigger position is reliable enough, it could be used intentionally to automatically determine component heights.
–Probe function: There is a conductive metal path from the needlepoint all the way up to and including the bearing outer race, so it would be easy to touch a contact here and use the needle to probe for any conductive objects (e.g. find the tabletop if it is metal, or some capacitive shenanigans for PCBs/etc.). Useful?

Tags:
Posted in General, gEEk | Comments (3)

Toward an open-source Pick and Place machine

June 2nd, 2010

So, there’s some really cool, empowering stuff going down these days with regard to manufacturing. Cartesian machines (i.e. CNC mills) are relatively simple to build from off-the-shelf parts; there are a bajillion people doing this and plenty of ready-made open-source designs available. More recently, hobbyists have gotten in on designing open-source rapid prototypers (3D printers); as a result, designs have now crossed the sub-$1000 threshold off-the-shelf, and you can even build a GPL’ed 3D printer that can almost replicate itself!

One thing that I haven’t seen cross the blood-brain barrier of proprietary commercial systems is pick-and-place machines that can assemble electronics. These things are badass; full of automated win and articulating robotic arms, but they’re also damned expensive: the crap ones start at >$10k and use literally a fishing-lure-and-weight type arrangement to peel back the tape covering tape-and-reel parts, so you have to keep resetting the weights. Those with more advanced / less manual feeders scale skyward from there. And of course, the software end of these things, especially machine vision algorithms to place parts more accurately, is some serious $ecret $auce. So… let’s change this!

Most of the “big stuff” is straightforward: The PCB layout software generates a list of coordinates for each part. A small vacuum needle mounted on a Cartesian head picks up each part from a known location, rotates it 90/180/etc. degrees as needed, and sets it down at its coordinates. It does not even need to be 100% accurate: surface tension of the solder during reflow will pull most minorly misaligned parts back into place.

The big barriers are:

1) Low cost / self-manufacturable feed mechanisms:
Electronic parts are packaged in several different ways, most commonly tape-and-reel, plastic tubes, or in trays. Each has a different, maybe cumbersome, way of knowing the location of the next part in the package and freeing the part from the package. Picking up stuff and putting it down is easy compared to dealing with the wide variety of tape and tube sizes reliably. Oh, and if your board uses 50 unique parts, you need 50 feeders. Hence the emphasis on making them cheap and mass-self-produceable, e.g. by CNC or casting or 3D printing.

and/or…

2) Machine Vision
For larger parts, once the first part is successfully picked (e.g. by human intervention), it is enough to know how many parts per inch of tape, advance the tape a known amount per pick, then just grab blindly for the part and plant it at its destination coordinates. But for smaller and finer parts, this is not accurate enough: the parts can be slightly off-center or crooked in their tape wells, and this becomes significant as the part size decreases. Professional machines use a set of cameras and image processing algorithms to recognize the part, find its dead center and correct any rotational error. In theory, a suitably good vision system would allow you to peel back the tape and just sprinkle the parts on the table, forgoing feed mechanisms entirely at the expense of some small manual labor. Actually programming this algorithm on the other hand…

Another nice thing to have would be:

3) Automatic needle swapping. Many more advanced CNC mills are able to spit out their current tool, e.g. a specific size drill bit (in a known location in a tool rack) and pick up a different tool. It would be nice for the pick and place machine to be able to change to smaller and larger needles/suction cups to handle large and small parts seamlessly. If not, placements can be sorted, e.g. smallest to largest, so that the needle only has to be manually changed a couple times.

I’ve made some very initial feasibility-study stabs at building such a machine, and begun building a bit of hardware. I created a separate page for this project with more detailed specs/documentation and progress so far:
Pick and Place Project

Tags:
Posted in General, gEEk | Comments (5)

Throwies overtake Kendall/MIT station sculpture

July 13th, 2009

Blinking RGB LED throwies adorn the “Steaming Globe” sculpture near the Kendall/MIT station just after the 4th of July fireworks show. No idea how this could have happened.

Kids had a blast pulling them off and throwing them back onto the globe (and each other!). The whole rest of the night as we walked around, we saw blinking kids.



Posted in gEEk | Comments (0)

Fun with MIDI, CNC and vector maths (mid2cnc.py)

April 3rd, 2009

More playing:
Castlevania end credits
Tetris
Mario Bros. theme

Update: I fixed up the script to pull (usually) proper timing from the MIDI, threw together some minimal documentation and released it to the public (see link below).

Downloads
mid2cnc.py, sparse documentation and samples

Basically, it’s possible to compute a combination of (distance, feedrate) along an axis that will cause the stepper motor for that axis to spin at an exact frequency corresponding to a musical note. With a little vector magic, the same can be done for (x, y, z, feedrate) to produce chords as the machine follows a 3D line through space.

(For anyone wondering, the song is Jonathan Coulton’s Still Alive, better known as the end credits theme from Portal. The MIDI is from topazstorm.)

*whew* That was the easy part. The real magic will happen in a future post, if I ever get around to it :-) Hint: The fact that notes can and do swap arbitrarily among different axes (while still sounding passable) is important.

How This Works (for CNC-heads):

We have code G1 [pos]x F[feedrate] for linear interpolation at a specific feedrate. Thus need to convert between feedrate in IPM and frequency in Hz (steps per inch or inches per step). My machine as currently configured is 36000 steps/in, so if we wanted it to play middle A (440Hz) (440*60 = 26400 steps/min) we would want to move along a single axis at feedrate (26400/36000 = 0.7333..) IPM.
or more generally, (freq/600) IPM.

Here are the frequencies for one octave. The formula to convert semitones (notes) to their actual frequencies is

f = fRef*2^(x/12)

where fRef is an arbitrarily chosen reference frequency corresponding to a specific note, and x is the number of semitones difference between the note you want and the reference. Middle A (440Hz) is as good a reference note as any, and its MIDI note number is 69, so the formula to calculate frequency for any MIDI note number becomes:

f = 440*2^((x-69)/12)

; C4 = 261.63Hz
; D4 = 293.66
; E4 = 329.63
; F4 = 349.23
; G4 = 392.00
; A4 = 440.00
; B4 = 493.88
; C5 = 523.25

And the G-code with the resulting feedrates to play this scale on my machine:

G1 X1 F0.43605
G1 X2 F0.48943333333333333333333333333333
G1 X3 F0.54938333333333333333333333333333
G1 X4 F0.58205
G1 X5 F0.65333333333333333333333333333333
G1 X6 F0.73333333333333333333333333333333
G1 X7 F0.82313333333333333333333333333333
G1 X8 F0.87208333333333333333333333333333

; Unfortunately, our note duration is now frequency-dependent. If we wanted it to play for 1 minute, we should make the distance
; equal to the feedrate in IPM (or 1/60 of that to play for 1 second, etc.). Easy-peasy so far.

Now let’s complicate things a bit. Suppose we want to play 2 or 3 notes at once. G-code linear interpolation scheme is that in, say, an XYZ move, all the axes arrive at the same time. Feedrate is the speed the tool moves along this *vector*, not the speed of the fastest/arbitrary axis. In other words, you cannot specify individual feedrates for the (x,y,z) axis moves, only one for the resulting vector as a whole. So, since the vector that results from adding 2 ore more axis moves will always be longer than either of the individual axis moves (for the 2-axis case, think the hypotenuse of a right triangle) the feedrate we set will be faster than the highest note, and will depend on the individual notes and their contributions to that vector.

Assume the bog-standard C-E-G chord. To play each on its own for 1 second…

G1 X0.0072675 F0.43605 ; move this distance
G1 X0.0164238 F0.54938 ; move 0.009156333…
G1 X0.0273126 F0.65333 ; move 0.010888833…

…but we want to combine these into a single (x,y,z) vector at a single feedrate.
The vector is obviously (0,0,0 to .00726, .00915, .01088), and its length is given by sqrt(x^2 + y^2 + z^2). Remember we are playing all three notes for the same length of time. The vector has lengthened, but the desired playing time has not, so we need to choose the feedrate for this new distance that yields the same travel time.

Regardless of how the length or rate changes, the (x,y,z) components remain proportional to one another. Just pick one of the individual axes/notes as a reference, compare the final vector length to the length of the reference note and bump the feedrate proportionally to the change in length. In this case we arbitrarily select the highest note as the reference, and the ratio of the final feedrate (unknown) to the reference feedrate (known) should equal the ratio of the 3D vector length (known) to the reference length (known). It’s almost too easy!

3D Vector length: 0.015975658808286373765422932349422

Feedrate: (newlength/oldlength) * oldfeed

= 1.4671598699591015644580950363551 * 0.65333 = 0.9585395578403798251074072301019

G1 X0.0072675 Y0.009156333 Z0.010888833 F0.95853955

Just remember that *any* change of any note requires computing a fresh new vector, so long notes will have to be split up wherever another concurrent note changes.

Tags: , ,
Posted in gEEk | Comments (26)

(Also: An experiment…)

April 3rd, 2009

In the last post, I made the unspeakable blargger mistake of linking to an article on a news site, which means in 7 days or so, instead of said article this link will return absolute crap and/or a “Buy membership now!” nag screen. Trying to keep up with such link rot (if anyone bothered) is a problem that grows linearly with the number of posts/articles written, until it reaches 100% of the blogger’s time and he/she/subject/verb has to stop writing any more posts and become a forest ranger. I’ve ranted this before with some possible solutions, but as you may have guessed based on my project completion record to date, didn’t get around to it (got maybe as far as writing a toy script that wget’s pages and stuffs the contents into a database record).

So a little experiment: Instead of linking to the article directly, I linked to a carefully-constructed “I’m Feeling Lucky” Google query containing unique phrases contained in the article. The idea is that as the site shuffles stuff around / deletes content / recycles numeric links, rather than a 404* the link should preferentially return a clean copy of the article from somewhere else on the Internet if it exists (syndicated copy, fulltext copy-paste into a blog/slashdot post somewhere, etc.).

Let’s see if it lasts any longer than a regular news-site link!

(For anyone interested, the actual query is:

http://www.google.com/search?q=%22A+company’s+backroom+mass+of+servers+and+switches+is+cloudlike.+So+are+social-networking+sites+like+Facebook+Inc.%2C+or+the+act+of+buying+a+book+on+Amazon.+Some+clouds%2C+like+Google’s+email%22&btnI=Lucky

The “%22″ at the beginning and end of the query string itself is the URL-safe encoding for a double-quotation mark (ASCII code 0×22), so that the quote marks in the query don’t conflict with the quote marks in the <a href=”…”> tag. To simulate a click of the “I’m Feeling Lucky” button, replace the button-type code that normally appears in the query (btnG=Search) with “btnI=Lucky”. Also note that apparently Google limits queries to a maximum of 32 words.)

* Modern commercial sites seldom, if ever, actually return a HTTP 404 code when a document is not found, since software including search-engine spiders detect these and drop 404′d pages from their listings. it’s far more profitable to pretend the user/bot has reached some kind of non-error document, swap in a generic landing page and stuff it full of keywords and advertising.

Tags: ,
Posted in gEEk | Comments (0)

Optical Mouse Hacks: 2D Micropositioning using cheap mouse cameras

March 22nd, 2009

Optical mice work by pointing a tiny cheap camera at the surface of your desktop, tracking the motion of ‘interesting’ points in the surface texture (woodgrain, imperfections, highlight/shadow) as the mouse slides around over it, and converting this to an X and Y motion. An LED is used to light the surface beneath the sensor, typically at a very low angle to help highlight any surface roughness (so the sensor still works on rough, but solid-colored, surfaces such as paper). Many of these sensors allow you to read out the raw image, too. Historically, the sensors in optical mice have been a standalone chip with SPI interface, leaving a separate microcontroller to handle button clicks and PS/2 or USB interface – so you could hack a cheap optical mouse to output position or image data for unique scanner or robotics projects. Unfortunately, more and more of these high-volume, low-cost devices are moving to all-in one camera+micro+USB chips under an epoxy blob, so you can’t just buy any old optical mouse and expect any access to this internal data.

Videos:
Absolute microposition sensing using image recognition
Relative position sensing (i.e. just like a mouse) using the DELTA_X/DELTA_Y registers
Downloads:
Arduino Library


Naked mouse cam and lens wired to a microcontroller

Fortunately, standalone SPI sensors are still alive and well. Mouser.com (no pun intended) sells some of these (Avago ADNS-2610 and ADNS-2620) for the exhorbitant price of $1.56 each. It’s a CAMERA for a buck fifty. Not exactly a *good* camera (grayscale, 18×18 resolution), but you can still do some neat tricks with it. Of course, you will still need a cheap optical mouse to steal the lens off of (or maybe an old CD player, etc.).

If you want to be all lame and boring, you could use this mouse camera as, well, a mouse. An onboard DSP is constantly watching the surface below as it slides by, giving you an up-to-date relative position (DELTA_X and DELTA_Y) just by reading a pair of registers. Each ‘delta’ reading contains the number of +/- pixels the mouse has moved in each direction since the last time you read it. Since you are only reading 2 registers, you can read this information at very high speed. There are some additional registers that will give you the max and min brightness, sum of all pixel values, and a ’surface quality’ value that represents the number of trackable points (divided by 2) under the imager.

But if you want to dig deeper, a builtin diagnostic feature lets you bang some other registers and return the entire image under the camera. A few things worth mentioning before you go further, though: this IS meant as a diagnostic feature only; they sell these things as mice and not cameras after all, and this feature is not the best implemented. There are 324 pixels (18×18 array), but you can only grab one pixel per frame. So when you get the image, you are actually seeing pixels composited together from 324 separate frames across maybe 1/2 second. If the camera is moving during this time, you’ll get a garbled image, so if you have this puppy strapped to a robot to take pictures (or position the robot), your robot has to stop for pictures. Also, your maximum full-image rate is only a couple images per second.

Following are some demos of monochrome and color image acquisition, surface identification and micro-position sensing down to the um range.

Circuit:
The ADNS-26xx parts only require a couple external components: an oscillator and a couple capacitors to stabilize its power supply and internal reference voltage. The oscillator frequency (about 20MHz-25MHz) is not critical; any cheap ceramic resonator will work fine here. So your complete parts list is:

1x ADNS-2620 mouse cam
1x 24MHz resonator (speed not critical)
1x 2.2uF capacitor
1x 0.1uF capacitor (optional but recommended power-supply bypass; value not critical)

Grabbing images:


The sensor’s great for reading that pesky fine print.

Above is a sample image taken from the sensor, looking at the little “Equal Housing Lender” glyph on some credit card junkmail. See below for some more. The process is straightforward; write once to the PIXEL_GRAB register to arm it, then read it 324 times (18*18) to read out the image bytes starting from the top left pixel. (Or use my Arduino library ;-)

And no, I’m certainly not the first to think of this. See here for a demonstration where someone combined the image and position readouts to use the mouse as a crude handheld scanner. I haven’t tried it, but I wonder how well this can see your fingerprints if the angle is right. (I assume not very well, otherwise mouse companies would have already enabled frame-grabbing on USB mice and tried to sell it as combination mouse and biometric ID thingy.)

Color imaging:
The grayscale sensor can be used as a crude color imager by replacing the standard red lighting with an RGB LED, and taking one frame with each color lit in turn. Depending on the LED, you may have to scale the R/G/B frame data differently for more accurate color representation. I assume like most photodiode technology the mouse cam pixels are most sensitive to the red-IR range, but the LED I used had a pretty weak red, so it was kind of a wash. (The image here is scaled red=0.75, green=1, blue=0.75).

2D position finding using the “Christopher Carter Algorithm”:
Very simple position-finding routine I wrote for testing purposes; named after a magician’s trick where the blindfolded practicioner (renowned hypnotist Christopher Carter, in the first case I saw it) “reads” a name written on a dry-erase board by swiping a finger across it at a few different heights. This is a similar idea, using a basic edge-detection to identify regions (“where to read”), then read them by the brightness at the center of each region.

In this method, you create a known optical pattern (in this example I used Gray Code) and apply it to the surface whose position you want to measure. Then aim the camera at it so that it looks at a small subset of the optical pattern at any given time. Ideally, each ‘pixel’ of the optical pattern should cover a 2×2 or more (3×3 or 4×4) pixel area on the sensor, since the optical pattern and the sensor’s pixels will never be *perfectly* aligned, and thus will blur across a couple neighboring pixels. Now you can identify the unique pixel pattern under the sensor and match it its position in the full optical pattern.


In a project at work, we needed to know how far a visual indicator pin on a piece of machinery was extended at any given time, and whether its position was in tolerance (reducing human observation error in dark and foul weather conditions). Since the sensor could not be permanently attached, we also wanted to be able to measure slop or shifting of the sensor itself relative to the pin, which would produce an incorrect reading. The small space, large pin travel and need for sensor cross-checking made common 1-D proximity sensors less attactive.

Definitions: The “pixel grid” is the actual sensor array. For ADNS-26xx, this is always 18×18. A “region” is one individual mark in the optical pattern, corresponding to a 3×3 (etc.) region of the pixel grid as mentioned above. The “region grid” is the array of these regions overlaid somewhere on the pixel grid. For example, with an 18×18 pixel grid and each region 3×3 pixels, the region grid overlaid onto the sensor can be as large as 6×6.

By performing this 2-stage lookup (find region grid offset on pixel grid, match region grid to known optical patterns), the total computation time is reduced by mainly working with only a small subset of the pixel data (the region grid), and the positioning resolution is at least (region size) and at most (pixel size). Working with only the center pixel of each region, to the extent possible (rather than e.g. averaging the entire region’s pixel values), is also beneficial since the regions may not be perfectly aligned to pixels and the focal plane at close range is very narrow (<1mm), thus the image may not be completely in focus – especially if looking at a curved or otherwise 3D surface. So all the pixels toward the edges of the region will tend to dilute the reading.


Absolute 2D position encoding/decoding using a Gray Code pattern. Position is resolvable generally to 1 pixel, in this case measured at about 2.4 mils (about 70um). The top-right shows the raw image with region grid (black squares) overlaid aligned to the strongest edges (pink crosshairs). The bottom-left shows the edge-detection itself, and finally, the top-left shows the recovered optical pattern. The actual position is the index of this pattern in the known fullsize pattern + the region grid’s offset.

Assuming an 18×18 image sensor:

Perform edge detection by taking the derivative of the image. Embedded systems such as Arduino are barely suited for non-integer math, let alone calculus, but we can take a poor-man’s “discrete derivative” easily by just subtracting neighboring pixels. Neighboring pixels on a uniform surface will not differ by much, so subtracting two neighbors will yield a low number, while along an edge, one will be very different from the other. We want to figure the vertical and horizontal edges separately. And we don’t care about the exact location of ALL the edges per se, just want to know on which rows and columns they occur. Once at least one good, strong edge is detected in each direction (horizontal and vertical), we know where to align the region grid so it is centered on valid regions.

For each horizontal row: For each pixel, its edginess (likeliness of being along a *vertical* edge) is given by the absolute value of (pixel – left neighbor) + the absolute value of (pixel – right neighbor).

v_edginess[row][col] = int(abs(image[row][col] – image[row][col-1]) + abs(image[row][col] – image[row][col+1]));

And of course that entire row’s vertical edginess is the sum of the edginess of all pixels in the row.

For each vertical column: Same thing, only going by columns, taking the pixel directly above and below. Again, the column’s edginess is the sum of the edginess of all the pixels in the column.

Obviously, the leftmost pixels has no left neighbors, and the rightmost pixels has no right neighbors (same goes for the top and bottom rows, they are missing neighbors on one side), so the easiest approach is to exclude them from the loops, e.g. for the 18×18 array, valid results start at (1,1) and end at (17,17). The result is an ‘edginess’ array of 16×16 pixels.

Once the region grid is positioned, threshold the region centers to black/white, then take the resulting region grid (4×4 in this example) and slide it around on an array containing the ‘known’ pattern until the best match is found. Obviously, in a real-world system subject to bad lighting, specks of dust, misalignment or misfocus, the match will not always be perfect. You might also want to know how well you can trust the measurement, so I compute a confidence value too. The confidence value is a function of the absolute % of regions matched, and the difference between the best match and the next best match. For example, if two different positions matched equally well (even if they are both “pretty good” percentage wise), you can’t uniquely identify a position and so your confidence must be zero.

Another thing briefly tested was to place an LED behind the pin and observe its side profile (Alfred Hitchcock Algorithm?), which worked surprisingly well.


Side profile of the pin showing the lower part of the indicator groove.

Tags: , ,
Posted in gEEk | Comments (15)

NinBendo (cont’d): Zero-knowledge, realtime music tweaking example

February 28th, 2009

This is a followup to this post.

Quick video example of finding and bending the music data that plays during Super Mario Bros. 3’s World 1 map, using the FCEUX emulator’s advanced 6502 debugging features. Full-screen if you’ve got it – the video did not survive compression well, and I don’t feel like investing hours tweaking around with it…

Video: Using FCEUX features to bend SMB3’s World 1 map music

Once on the screen of interest, go to the Debug menu and open the Trace Logger window. Tick the two ‘Only log new data…’ boxes, choose a filename for ‘Log to file’, and press Start Logging. These options require the Code/Data Logger to also be running, so FCEUX will prompt you to open it (hit Yes). Pay attention to the ‘Bytes logged as data’ count, it is slowly increasing as data is fetched from the cartridge. Most of the game code is running a complete loop every frame, so the ‘Bytes logged as code’ count should max out quickly. Likewise, MOST of the data being accessed here (e.g. sprites, etc.) will go through their entire rotation within a second or so, but the music takes over 20 seconds to do a complete loop (you can see the data byte count roughly keeping time with the music). Thus the last >20 seconds of data in the logfile will consist of music data fetches. Open the log, scroll near the bottom and notice the resulting disassembly, consisting largely of e.g.:

$E47A:B9 71 A7 LDA $A771,Y @ $A7C5 …

In English that is: Cartridge address $E47A onward contains an instruction with data bytes (B9 71 A7). The first byte is a CPU opcode (LDA $xxxx), telling the CPU to load the data at memory address (specified by the next two bytes, $A771) into its A register. Some subsequent code (purposely omitted from your trace log since it runs every time new data is fetched) processes the sound data. Thus corrupting one or more of those address bytes will cause incorrect sound data to be fetched and parsed, causing audible glitching depending on what the fetched data tells the sound loop to do.

Tags: , , , ,
Posted in gEEk | Comments (1)

NinBendo – circuit bending by corrupting 8-bit game code.

February 28th, 2009

Yeah, back in junior high I had not enough friends and too much time, and discovered that keying in random Game Genie codes would sometimes cause a NES game to (harmlessly) glitch out in interesting ways. :-p Some codes just locked up the game (drat!), while others caused screen glitches, messed with colors, and rearranged levels. Still others would screw up the game music or sound effects. I was always strangely mesmerized by the bleepy sonic barf of a good sound loop crash.

Of course, now that I’m all old and exposed to the Internets, I come to find out there are entire groups devoted to pretty much exactly this–glitching out electronic toys to produce interesting sound effects (circuit bending). So for those folks, here is some info and samples from codebending on the original NES. Hardcore circuit benders might consider this software-bending stuff cheating since the case never comes off ;-)
Read the rest of this entry »

Tags: , , , , , , ,
Posted in gEEk | Comments (2)

Better Better DXF Output for Inkscape (layers!)

February 21st, 2009

I started using Inkscape, a sweet open-source vector graphics program, to produce (and/or steal from the internet and convert) designs suitable for carving on the CNC as Inkscape has a plugin to export the file as a .DXF. Converting some files, I discovered the current export script does not correctly handle all types of transforms, so some parts of the file may export out-of-proportion to each other or in strange size units regardless of the drawing units of the original drawing (Inkscape’s internal drawing unit is apparently equal to 1/90 of an inch, wait, wtf?). Also, if the drawing contains curved (Bezier) lines, these will be exported more or less as-is (DXF splines) and many free/cheap/itch-scratch-ware programs will not handle the resulting file (since the ‘correct’ representation or interpretation of splines is never disclosed in the published DXF file specifications, so everyone kind of does them in their own way, with less-than-stellar results).

Bob Cook noticed these limitations and updated the script to fix many of the ‘unusual transforms’ scaling issues, and convert Beziers to standard polylines that any program will import. It also adds some support for layers, including special ‘drill’ layers whose drawing objects will be output as single points (no lines) for hole drilling.

In theory, the layer support as he implemented it ought to work (it’s correct and in conformance with the DXF spec, which allows drawing objects to be assigned to arbitrarily-named layers throughout the file). In practice, many of the same free/OSS, low-cost and weekend-warrior tools do not handle this any better than splines. I dug up a copy of the DXF spec, played around a bit and found that these programs expect all layers to be formally declared in a DXF LAYER table in the header section of the file before use. So here is an update to the export script that generates a proper LAYER table, allowing a wider variety of toolpath generating programs to import them correctly. So far it has been tested with ACE Converter and CamBam and seems to work well, but as always this is a quick n dirty, not exhaustively tested script and there is no lifeguard on duty. (Inspect the imported files for problems before commanding your big machine to cut them!)

Better Better DXF Output for Inkscape

Just unzip into your \Inkskape\share\extensions directory. Note that the updated ’simpletransforms.py’ replaces an existing file.

Note: There is still an outstanding issue with Grouped objects in Inkscape being exported with incorrect size. As I understand it (assuming the document structure sent to export scripts is substantially an SVG file), transforms are applied at the Group level, which is sort of a container that has the actual drawing objects (and possibly further nested groups) as its children. Guessing that to handle this correctly, rather than looking for transforms at the node itself, it must also maintain a stack of transforms that have been applied at the node’s parent level, and parent’s parent, etc. For now, it is an easy workaround to ungroup everything before export. Maybe someone with freetime can update this and release it as ‘Better Better Better DXF Output’ :-) (b3dxf?)

Tags: , , , ,
Posted in gEEk | Comments (12)

Cypherpunk’s Wet Dream meta-entry

January 21st, 2009

I once said that this blog would eventually reach a point where any possible entry could be expressed as a sum of references to previous entries. In this case, it’s this one, this one and this one.

I have maintained that a point will be reached where plain old ordinary Web sites will be forced to turn on SSL encryption by default, or otherwise resort to client-side validation to ensure the page content hasn’t been tampered with during transit. Not because they are running online shops or otherwise dealing with sensitive information – to ensure their users view the original site as it was meant to be seen, protect their users against malware injected by man-in-the-middle attacks, protect/ensure their ad sales, and protect themselves from liability (lost sales from angry customers, frivolous ADA/etc. lawsuits, computer repair bills) arising from unauthorized third-party “enhancements” to their site. And I figured the detonator for all of this (besides Comcast’s broken BitTorrent filter) would be local-yokel small-town ISPs, where bored and too-clever midnight admins sit, Perl Cookbook in hand, trying to make a few bucks on the side by replacing random Web sites’ ads with their own, or injecting other forms of malware into customer HTTP streams to gather saleable profiling data.

Nope. It’s the big boys. Among them: Charter Communications, one of the world’s largest ISPs, and British Telecom have secretly tested, or intend to test (respectively) technologies against their paying customers which do exactly that. According to an internal British Telecom memo (fulltext PDF via Wikileaks), the company partnered with online marketing company Phorm, which specializes in consumer profiling and delivery of targeted advertising. According to Wired,

“From late September to early October 2006, British Telecom secretly partnered with Phorm to let the company monitor and track 18,000 of the BT’s customers. Phorm installed boxes on BT’s network that redirected web requests through their proxy server.

Those boxes inserted JavaScript code into every web page downloaded by the users. That script then reported back to Phorm the contents of the web page, which Phorm used to create ad profiles of a user.”

The report goes on to detail the ability of the Phorm proxy box to intercept requested pages and replace the site’s advertising with its own, based on the collected profile for that customer. The report also indicates several deleterious side-effects of this injection, such as flickering problems on some Web pages (which led users to believe their PCs were infected with spyware), frequent browser crashes, and insertion of the rogue code when users tried to post to Web forums. However, they concluded that the test was “successful” since no user was able to successfully pin the blame on BT/Phorm:

“The operation of the system does have noticeable side effects, which included web-page tag insertion and navigation bar flutter.

From the postings, no user correctly determined the source of these effects and users did not post that the system was causing poor performance.

However all postings suspected that their machines had a virus, a malware or a spyware infection.”

*sigh* Remember kids, you (probably) heard it here first. Let’s hope that in the brave new world of encrypt-everything-to-avoid-getting-fucked-by-ISPs, Firefox 4 doesn’t continue to perform that tired 5-warning song and dance every time you visit a non-corporate Web site.

Tags: , , , ,
Posted in Rants & Rambles, gEEk | Comments (0)

Trance vibe vs. Windows Vista x64

December 13th, 2008

So I have started getting support emails – “Hey, how do I get your hardware to work in Vista?” Seeming invariably to be the 64-bit version. That’s weird, as far as I know there is a 64-bit build of the drivers included…

Of course, you may have correctly guessed that as an IT semi-professional, I
1) don’t let that poisonous crap anywhere near my home/work machines,
2) am not keen on buying a copy of every Microsoft OS just so I can test free give-away software against some obscure bug(s).

Last night I was able to ‘borrow’ a copy of Vista 64 and set up a test machine. And I discovered the cause of the problem! You can thank our good friends at Micro$oft for this: Vista-64 will not allow drivers to run unless the driver’s author is willing to pay for a digital signature, which starts at US$499 per year :-(

There are some apparent (but ugly) workarounds:

If you press the F8 key right as Windows is beginning to boot, you should get a black screen marked ‘Advanced Boot Options’. Select the last option – “Disable Driver Signature Enforcement” – and press enter. This should allow the driver to operate (bypass the microsoft tax) until the next time you reboot. Unfortunately this means that even if it works, you will have to repeat this step EVERY time you start the computer if you want to use the device.

You could try typing in a command prompt: bcdedit -set loadoptions DDISABLE_INTEGRITY_CHECKS (yes, ‘DDISABLE’ is correct and not a typo). But it appears M$ have disabled this in some later updates.

You could get friendly with hackers and install a sneaky loader on behalf of your customer (sad when forcing a product to work as intended requires “sneaky”) – until you get caught and they not only add your drivers/loader to the global blacklist that gets pushed out to every Vista system with the “security updates”, but revoke your expensive certificate with the CA so you can never program drivers again (or get a new certificate, unless you can find a CA that missed the memo).

You could force your customers to get friendly with hackers to bypass signing more completely – well, until M$ releases a patch around it.

* * *

I wonder if it is possible to hack around on my (hardware developer) end. The hardware is a USB device, the firmware source is published and the device can receive firmware updates. Possibility for special “F***in’ Vista” firmware build: If the device detects a cold-boot, device enumerates as a USB keyboard, sends simulated ‘F8′ keypress and selects the Disable Signing boot option without any user intervention required. Feasible? Legal?…

Tags: , , , , ,
Posted in Dildonics, gEEk | Comments (3)

VMWare Player Network driver (and video, SCSI, etc.)

December 6th, 2008

Problem: After installing some operating systems such as Vista* in a virtual machine (i.e. as a ‘guest’ OS) under VMWare Player, they cannot access the internet because they don’t have a driver for VMWare’s virtual network card.

Solutions: This driver (and many others such as SVGA, SCSI, sound) are available in the ‘VMWare Tools’ package. Unfortunately this does not come with the free(beer) VMware Player, only higher-end products such as Server and Workstation that require payment and/or a ‘free’ (revocable at any time; costs your time and one valid email address) license key. They’re also a rather hefty download to scavenge out one lousy driver and copy it over. VMWare Tools includes .iso files, notably ‘windows.iso’ that can be mounted as a CDROM in the guest OS to install the drivers. This is the part you really want.

Windows.iso download direct from VMWare’s site: VMware ESX Server vmxnet Driver Update for Windows NT (.tgz file, use 7-Zip or similar freeware to extract)

This file contains basically an updated copy of Windows.iso (to fix a bug in a particular old version packaged with VMWare ESX Server) and nothing else; no registration or 200MB downloads required. (Despite the ‘for NT’ description, the .iso contains the full set of drivers for other Windows versions.) Score!

* for Vista and maybe others, you may have to explicitly force VMWare Player to present a specific virtual network card interface corresponding to one of the drivers included with VMWare Tools: open the .vmx file for your virtual machine in a text editor, find the network section and ADD the following line for each card:

Ethernet[n].virtualDev = “vmxnet”

replacing [n] with the virtual network card’s number shown in the other lines of settings, e.g. ethernet0. The ‘vmxnet’ driver is included in the Tools. Other choices I have heard of besides ‘vmxnet’ for this field include ‘vlance’ and ‘e1000′, though I don’t know where or if a full list of possible choices is publicly documented anywhere. Of those options, only the ‘e1000′ card seems to have a driver available for Vista x64 (the Tools does not appear to contain 64-bit drivers).

Tags: , , , ,
Posted in gEEk | Comments (5)

Tease…

November 21st, 2008

It’s not quite finished yet, but here are some pictures of what I’ve been working on this week, when not making you-know-whats in my basement dildonics facility.



Tags:
Posted in gEEk | Comments (0)

Petty Joule Thief

October 25th, 2008

You might be familiar with the original Joule Thief, a simple, homebrewable step-up converter often used to drive LEDs (with Vf of several volts) from a single 1.5V battery, or extract the last remaining juice from a battery that’s too dead for use in most real-world gadgets. The basic Joule Thief can suck power from low voltage sources where reasonable current is still available, but what if you want to go even lower? What if you want to suck juice from your neighbor’s WiFi signal originating just on the other side of the wall? RFID or other sensitive inductive-powering mutual-inductance shenanigans? Harvest power from a Peltier device across a relatively small thermal gradient? Solar-power a gadget on even the cloudiest of days? How about scavenging useful power from those annoying radio broadcasters who can find nothing better to talk about than celebrity gossip and which sports mogul was caught with steroids this week?

Recently I discovered a copycat energy-harvesting company trying to claim trademarks on the term “Joule Thief”, which, having been a staple of DIY electronics for about the last decade, cannot stand. So here’s a variation on the classic which a) timestamps the first use of another clever circuit name, and b) genericides the crap out of the bogus mark. So, without further crap, here is the Petty Joule Thief(r)(tm)(c)(processed cheese food):

This one, based on a monolithic IC designed for bootstrapping bigger step-up converters (Seiko S-882Z series), will start-up on voltage sources as little as 300mV, and continue boosting at even lower voltages, stepping it up to 2.4V – enough to drive most LEDs and a good many low-power microcontrollers these days. The circuit is not exactly innovative either (the off-the-shelf chip and a couple caps; basically right from the datasheet), but hey, 300mV guaranteed start! Unfortunately, actually laying hands on these chips is nontrivial for the average hobbyist; they’re not available on Digikey, or indeed any direct-sales establishment in quantities less than 300 units. You might get lucky if you call up your nearest Seiko sales rep and beg really, really nicely for samples (an office at an engineering company and a big mahogany conference table might help). So really this is more of an excuse to get the funny name out there while we wait for these guys to grow a clue and sell on Digikey, or someone like Sparkfun to buy a reel and start selling them by the each.

Unlike the real Joule Thief circuit, this chip implements a switched-capacitor charge pump scheme rather than an inductive one. Both require converting a DC source to AC using a low-power oscillator, but the similarity ends there. Imagine wiring a 1.5V AA battery to a breadboard and placing a capacitor across it, which of course then charges up to 1.5V. Now yank the charged capacitor out and plug it back in so that the pin that was on the battery’s “-” terminal is now on the “+” terminal, and the one that was on the + terminal is now tied to your load. The 1.5 of the battery is now in series with the 1.5V on the cap, so there is now 3V at the load.

The capacitor on the input (10uF or so should be plenty) is for power supply bypass; this may be helpful where the input source is low-current as well as low voltage. For simple constant loads like an LED, the output capacitor should be maybe just a few uF or could possibly be omitted entirely (I haven’t tested this). For “bursty” loads (e.g. intermittently-running sensor / microcontroller), the output capacitor should be sized large enough so that the load can get its business done before the voltage drops below a usable level. You could do some math, but experimentation is more fun. The chip’s output will automatically switch ON when the large output cap is full (2.4V), and OFF again when the voltage drops to about 1.8V.

The efficiency of boosting power from 0.3V to 2+V is not great, but it does allow you to use many extremely low-voltage sources (maybe at low duty-cycles, like a once-per-hour wireless sensor/transmitter) that otherwise wouldn’t be usable at all. Consider the possibilities…


Crap to non-crap generator. Patent pending! (yeah right) And no, this is not a very efficient way to harvest radio waves, but it shows the concept.

Tags: , , ,
Posted in gEEk | Comments (2)

Weatherball

October 18th, 2008

Last night I finished throwing together a workable version of the Weatherball, currently displaying a color code at the end of my flagpole to indicate whether tomorrow holds any interesting weather. Apparently cities and radio stations have been doing it since the 1950s, but now I have my own! The data is grabbed from the NOAA’s National Digital Forecast Database server (XML) using a quick C++ program, and currently acts on five variables: chance of precipitation, chance of hail, chance of tornado, chance of extreme wind, and cloud cover percentage. Any ‘interesting’ values in these fields are evaluated in order of decreasing importance (beginning with hail/tornadoes), and the most significant weather condition is sent to the das Blinkenlichten node in the ball at the end of the flagpole.

In the spirit of virtually all known Weatherballs to date, here is a not-very-catchy jingle expressing the color code:

If the weather ball is yellow/green, the sun’s expected to be seen
If the weather ball is gray, anticipate a cloudy day
If the weather ball is blue, it probably will sprinkle too
If the weather ball’s maroon, be prepared for a typhoon
And if the weather ball is red, forget the beach – head for the basement instead!

(And if the weather ball draws half an amp, the electronics have gotten damp – the Blinkenlicht inside the ball has been outside for nearly a year (just waiting for me to get around to writing the software) and seems to still work fine, but I really should weatherproof that sucker.)



Weatherball showing no interesting weather for tomorrow (yellow-green). Know what it needs now? More Power!


Here are the main parts – the ball is supposed to be a curtain rod capper.


The program to fetch weather reports from the interwebs and drive the ball

The DON’T PANIC flag* (Hitchhikers Guide reference; the house number is 42) is showing a bit of weathering, but is still intact. The flag pole is a piece of lightweight enameled metal rod from the big-box hardware store, intended for hanging stuff in closets. The bubbly clear ball on the end is a decorative curtain-rod endcap from Ikea. A set screw on the side allows it to be attached to rods of various diameters. The exposed clear plastic extends through the inner diameter of the endcap some on the inside, allowing the LED node placed in the base to light up the ball (though not brightly enough for my tastes; may beef it up a bit later). The material can also be drilled out to embed the LED further into the ball, if desired.

* If McCain gets elected, it will be replaced by a bright red PANIC! flag, and the weatherball recoded to display the current terrist alert level. It will operate briefly in this manner while I search for a homebuyer and a cheap one-way ticket to Canada…

Tags: , , , ,
Posted in gEEk | Comments (0)

Assembler Interpreter for microcontrollers – sane?

October 1st, 2008

I’m thinking of how much work it would be to write an assembler interpreter in PIC assembler. Probably sounds like the dumbest idea in the world, right ;-)

I’ve been toying with this idea lately for sort of futureproofing microcontroller-based designs, and adding some new possibilities for specific applications (polymorphic / self-modifying code, security applications, Arduino shields with their own drivers built in, etc.). Basically, the ability to load executable code from some arbitrary source and run it from RAM, the way we’re used to with general-purpose computers. The key problem in this idea of course is that typical microcontrollers can only execute code from their internal Flash memory, not RAM. There are few hacks out there that straddle the line between bootloading and execution, e.g. load code from (arbitrary source) and write it to an unused block of Flash, then execute it, then load some more code over it, etc., but this could wear out Flash memory pretty quickly. The only way to execute something directly from RAM is if it’s an interpreted language. Rolling my own interpretive language and its interpreter in ASM doesn’t sound like much fun, let alone getting anyone else to adopt it. It seems like the “least-work” approach would be for the interpreter to take its input in the form of MCU opcodes directly, looking them up in a jump table and executing the corresponding instruction from Flash ROM. That avoids having to write your own language and some complicated parser for it, and documentation for the language, and debugging tools, and…

This simplistic explanation works for basic operations (register reads and writes; you could use this to bitbang some new piece of hardware on the GPIO pins that didn’t exist when you released your gadget), but breaks down a bit when dealing with handling calls/gotos and code addresses, and where to safely stash all the interpreted code’s variables. I think I need to put a bit more baking into this idea for that reason, but it seems mildly promising so far.

(And no, I’m evidently not the first person to have this idea. When searching to see if someone had already done it, no working implementations, but Michael Millikan mentions a similar idea on PICList (see Mar 3 2004 entry).

Tags: ,
Posted in gEEk | Comments (1)

Fixing Dell Precision T3400 USB not working

September 30th, 2008

This is an update to a previous rant about the mysterious Windows XP “Dee-Dunk” error (and the novel concept of presenting an “error message” when an error condition exists), possibly in conjunction with broken or intermittent USB functionality. This post is mainly for Googlers – my friends are more than welcome to skip it.

I haz solved the mystery! It turns out that some Dell Precision T3400 machines (my work machine was one of them) ship with buggy/broken BIOSes and/or chipset support. Anyway, to fix:

Worm your way onto Dell’s support site for updates, enter your model number; download and run the following three patches:

  • BIOS Update (T3400A08.EXE, or whatever is newest)
  • Chipset Software update (R174616.exe)
  • Desktop System Software update (R160758.exe)

The above are intentionally not linked; the filenames and/or URLS may shift around as newer versions of this crap come out. Also, exact support packages may be different for other Dell products exhibiting the same malfunctions.

Symptoms include:

  • USB devices do not work, or only work intermittently (every Nth reboot); behavior may change slightly by enabling/disabling different combinations of USB ports in the BIOS (or this may be a placebo effect on my part, who knows)
  • Dreaded “Dee-Dunk” noise shortly after Windows desktop appears
  • USB devices such as keyboards, mouse, etc. work for a while, then mysteriously stop working until machine is rebooted
  • “USB Device Not Recognized”…
  • “There was a problem installing this hardware: <blah> The device cannot start. (Code 10)”
  • After installing a certain USB driver, machine crashes/hangs with a black screen for several minutes before the Windows desktop appears (may depend whether the corresponding device is plugged in)
  • Machine hangs when trying to install USB device driver
  • Software hangs trying to scan the bus or access a USB device

Tags: , , , , , , , , , , , , , , , , ,
Posted in Rants & Rambles, gEEk, work | Comments (7)

WinLIRC stuff

August 13th, 2008

Yes, it means I’m hacking around on a MythTV setup again. LIRC is Linux Infrared Remote Control, a program for receiving keypresses from a remote control (TVs, etc.) on the computer, and/or blasting out simulated remote-control keypresses. WinLIRC is the same thing, for a Windows box*. Its documentation is a bit lacking however, so this is just a post to save the time of people who Google the error messages and wind up here.

In short: Upon first run, the program expects “Learn” to be the first and only option you ever think about touching (not “OK”, which you, like me, probably thought was the logical choice). And it is expecting a “.cf” file for its config file, not a .cfg or .rc or any of the others suggested in the Config ‘Browse…’ dialog. On first run, type a fresh new (not yet existing) file name (ending in .cf) in the Config box and press Learn, and the resulting steps will create this file. Do not select ‘winlirc.rc’ as the config file, even if this is one of the two logical choices. (You can select ’sample.cf’ as the config file, but it probably won’t do anything useful with your remote.)

Also beware that the initial configuration screen defaults to “COM2″ as your initial port for some stupid reason. This does not mean that your COM1 or connected device are broken, or that COM1 was in use by another program, etc. It’s just a braindead default (and does not necessarily mean that COM2 is the best choice, or that your machine actually has a COM2 for that matter).

Error message: “WinLIRC failed to initialize. Would you like to change the configuration and try again?”

Solution: This occurs on the first run of the program, since no config file has yet been specified. If you already know you’re going this route, it might be worthwhile to look at the “sample.cf” file in a text editor to see what’s in there. If you’re just trying it out and want to see if your hardware works, just enter any old filename in the ‘Config’ box and press LEARN. (Again, not ‘OK’.)

Error message: “Could not create dialog boxes.” (In a dialog box…)

Solution: This unclear message means any kind of generic failure to read info about your remote from a config file, probably because the config file doesn’t exist or hasn’t been specified yet. It could also occur if the config file exists, but is in the wrong format, or corrupted, or otherwise does not contain the info WinLIRC is looking for (for example, if you chose ‘winlirc.rc’ as the config file).

*Heresy, I know. The Myth box is a real Linux system, honest. I’m trying the untested IR receiver hardware on my Windows box first since running it there is a double-click rather than dicking around with why the LIRC kernel driver is barfing errors, and that machine actually has a free serial port vs. the uncertainty of whether all this timing-based stuff has any hope of working over a USB-to-serial converter.

Tags:
Posted in gEEk | Comments (2)