Category Archives: Portfolio

Hacking a Digital Bathroom Scale

People all around the internet have been doing cool things with the Wii peripherals lately, including the Wii Fit balance board. Things like controlling robots or playing World of Warcraft.

But what if you just want one weight sensor, not four? The balance board starts to look kind of pricey, and who wants to deal with Bluetooth if you don’t have to?

I’ve had a couple ideas for problems that could be solved by a cheap interface to the weight sensor in a common digital bathroom scale. The kind you can get for $15 or so at the local big-box store. For example, I’ve pondered using a grid of bathroom scales as an input device. You could use it to emulate a DDR pad, and there might be new applications that could benefit from analog weight readouts on each square of the pad.

The other idea is really Scott‘s doing. He has a kegerator, and naturally we’ve been plotting to fill it full of all manner of sensors, actuators, and RFID readers. We’d like to have a continuous measurement of the keg’s weight, both to have some advance warning that it’s getting low, and to detect when an individual glass of beer has been dispensed. It seemed like if we could use the sensor from a digital bathroom scale, the filtered output would probably be accurate enough to detect the difference in weight from just one beer.

I’ve seen other projects to hack a digital scale. For example, this SD Card Bathroom Scale project uses a microcontroller to ‘read’ the LCD by decoding the signals used to drive it. This was a great idea, and he pulled it off quite well. But it requires a lot of wiring, and you’re still limited to the resolution and functionality of the original scale. I wanted to see if there was a simpler and lower-level way to hack a typical bathroom scale. And, for my particular scale at least, there is.

How a digital scale works

Old-skool analog scales (you know, with the needle that moved) were based on some clever gears and levers that converted pressure on the scale into compression of a big spring, then the spring’s compression into rotational motion that could drive a dial. But digital scales don’t really have any moving parts. They are mechanically designed to distribute your weight evenly to a bar or collection of bars which bend very very slightly under the pressure. Those bars are bonded to an electrical element that also flexes very very slightly, changing its electrical resistance. This is a strain gauge.

Inside the scale I hacked, you can see the two load-bearing bars. Each bar has two strain gauge sensors bonded to it. Measuring the difference in strain between the two sensors can tell you how much the bar is flexing.

Inside the modified scale

There are a lot of notable parts here:

  • There are two buttons mounted on the scale’s feet. These are connected in parallel. If either one is pressed, the scale will power on.
  • The vertical bars on the left and right are load cells, the mechanical parts that are designed to bend slightly. Each one has a tiny PCB with two strain gauge sensors. The two sensors share one common wire, so there are three wires going to each load cell.
  • The clip in the bottom-center originally held a lithium coin cell battery.

And on the main PCB:

  • A numeric LCD module, bonded to the PCB.
  • A microcontroller or ASIC of unknown variety. This is the digital chip that runs the scale- it’s a chip-on-board module which is soldered to the back of the main PCB.
  • Analog front-end. This consists of an LMV321 quad op-amp, a few transistors, and a heaping spoonful of passives. This amplifies and conditions the signal from the strain gauge sensors. I’ll talk about this more below.
  • Power switching. The analog front-end is very low-power, but to preserve battery life even more, the microcontroller uses a transistor to turn it off entirely when the scale is sleeping.
  • Hidden features! There’s a “CAL” header. If you short this header, wake up the scale, then un-short it, the scale will go into a factory calibration mode. The LCD displays some kind of raw reading in this mode, and it continuously updates.

Unmodified PCB

This is the only scale I’ve disassembled, so your mileage may vary. If your scale puts everything on a single IC, there may not be a way to hack it without building your own analog front-end. But if you get lucky (older scales may be more likely to use discrete parts) you may see something like this in the scale you disassemble. The separation of functionality into discrete analog and digital circuits makes this model of scale quite fun and easy to hack!

Reverse Engineering

This section will explain the process I used to figure out how this scale works. You might be able to use some of the same procedures on other types of digital scales.

  • Visual inspection: Noticed the op-amp chip, arrangement of the passives, how the strain gauges were connected, power switching.
  • Looked up a data sheet for the op-amp chip. Noted the power and output pins.
  • Used an oscilloscope to probe each of the four op-amp outputs, looking for a signal that seemed plausible for a microcontroller to measure. This would have to be either a fairly high-amplitude DC analog voltage, or some kind of variable-frequency signal.
  • Found this signal. Output D on pin 14 had three different kinds of waveforms: low when the scale is off, high when the scale is on but not actively measuring weight (microcontroller is doing calculations or updating the LCD?). When weighing, this pin is a pulse train whose duty cycle seems proportional to weight.
  • Traced this signal back to a pin on the microcontroller.
  • At this point, it might have been sufficient to interface to the scale by snooping this signal. But the pulse train is not present all of the time, so I’d have to have extra code to ignore the idle periods. And you’d have to simulate button presses to keep the scale awake. So, I wanted to figure out how to keep the scale in measurement mode all the time.
  • First step: Keep the analog front-end powered on. I traced the V+ pin on the op-amp back to a transistor that the microcontroller uses to power on all analog circuitry. I soldered a shorting jumper across this transistor.
  • Now when the microcontroller is off, the op-amp output is high rather than low. This means there must be some other signal that the microcontroller is outputting in order to put the analog frontend into measurement mode, or otherwise generate that pulse train.
  • Probed around the microcontroller with my oscilloscope, looking for interesting signals on the pins nearby where the op-amp signal enters.
  • Found another pulse train which was active only when the scale was in weighing mode. This signal seemed to be at the same frequency as the op-amp output signal. This one is normally low, but has brief high pulses.
  • At this point, I thought I had enough information to guess how the circuit worked. Traced where this signal goes, to verify. It is an output from the microcontroller which heads to a transistor in the analog front-end. I didn’t fully reverse engineer this, but I suspect it’s discharging a capacitor that’s used for integrating the analog weight signal.
  • Made the modifications discribed below, and hooked the analog front-end input and output up to a Propeller microcontroller. Verified my guesses by performing some experiments with the microcontroller.

Analog Front-end

This documents my understanding of how the analog front-end works in this digital scale. I didn’t reverse engineer the circuit itself, so this is really just a “black box” description based on observing how the circuit behaves.

The circuit’s input is a tiny resistance from four strain gauges. They are arranged as two independent load cells, each with two sensors that act as a differential pair. The front-end amplifies these tiny differences in resistance, and sums them into a single analog signal. For example, if the strain gauges were labeled L1, L2, R1, and R2 (two sensors each for left and right load cells), the analog summation would be:

Total = L1 – L2 + R1 – R2

This total is still an analog signal, and it’s fairly noisy. There would be a lot of different ways to convert this to a digital signal: a standard successive-approximation A/D converter, a voltage to frequency converter, an RC oscillator… This scale uses an approach that’s simple, cheap, and pretty accurate for situations where you’d like to dynamically make tradeoffs between sample rate and accuracy. It uses an integrator and comparator.

In this approach, there is a capacitor which can charge or discharge depending on the state of a signal from the microcontroller. I’ve been calling this the “Reset” signal. When Reset is low, the capacitor slowly charges at a rate which depends on the analog Total above. This is an analog integrator. When Reset is high, the capacitor discharges quickly. This voltage across the capacitor is fed to a comparator, where it’s compared to a reference threshold. If it’s larger than this threshold, you get a logic “1” out, if it’s smaller you get a logic “0”.

This starts to look a lot like a closed-loop feedback system. In fact, you can even think of it as an electronic equivalent to the old mechanical balance. Instead of balancing two physical weights on a lever, you’re balancing two electric currents which are trying to charge or discharge the integration capacitor. If the capacitor voltage is too high, you need to drain it a bit. If it’s too low, you need to let if fill up. If you keep the capacitor voltage oscillating right around the comparator threshold, it’s just like you’ve balanced a mechanical scale. Now you know how heavy the object you’re weighing is, because you know how much time you need to spend discharging the capacitor to keep it balanced.

I find this symmetry between the mechanical and electrical scale pretty elegant. It’s also practical- your accuracy is limited by electrical or mechanical noise in the circuit, and by your microcontroller’s timing resolution. But you can always integrate over longer periods of time in order to trade sample rate for accuracy. If you keep the capacitor balanced for a whole second, and add up how much time you spent discharging the capacitor over that second, you’ve just calculated the average weight with much more precision than you’d have if you measured the length of a single discharge pulse.

Modding the Scale

After figuring out the analog front-end, I really just wanted a way to use that by itself without worrying about the built-in microcontroller or LCD. This turned out to be really easy:

  • Remove the lithium battery and holder
  • Solder a jumper wire across the transistor that normally powers off the analog front-end. (This is visible in the photo below, near the red and black power wires.)
  • Cut three traces near the microcontroller: Reset signal out, comparator signal in, and button signal in. This separates the microcontroller from the analog circuitry, and it also prevents the microcontroller from waking up. It will stay turned off.
  • Solder a 5-pin ribbon cable to the board: Ground, Power (+3v), Buttons (optional), Reset out, Comparator in.

The wires on the left are power and ground. It’s hard to see here, but the traces corresponding to the three wires on the right were cut, between the wires and the chip-on-board assembly. From top to bottom, those wires are comparator, button, and reset.ย And that’s it! With that simple mod, the scale is ready to connect directly to any 3.3v microcontroller with two free I/O pins. I used a Propeller, but an AVR should work great for this too. If you’re using a 5V microcontroller, you’ll still want a 3v or 3.3v power supply for the scale. You may also want to limit the voltage on the reset output signal too, though I suspect this isn’t actually necessary.

Modified PCB

Software

I tested this mod using a PropRPM board and some jumper wires. All of the other stuff on the PropRPM board is unrelated to this project- no external components are necessary to talk to the scale, just two 3.3v I/O pins.

Testing the modified scale

The software is pretty simple. To measure weight, you need to toggle the “Reset” output on and off in order to keep the integration capacitor balanced around a comparator threshold. Pulling Reset high will quickly drain the capacitor, pulling it low lets the capacitor charge at a rate which depends on the total weight on the scale. You can take more accurate measurements by repeating this for more cycles, or take quicker measurements by repeating it for fewer cycles. On the Propeller, I use the system clock to measure the total amount of time that I spend letting the capacitor charge. Here’s a complete program that prints scale measurements to the serial port:

CON
  _clkmode = xtal1 + pll16x
  _xinfreq = 5_000_000
  PIN_SCALE_OUTPUT = 3    ' Pulse high to discharge
  PIN_SCALE_INPUT = 4     ' Output from integrator
OBJ
  term : "Parallax Serial Terminal"
PUB main
  term.start(115200)
  repeat
    term.Str(String(term#NL))
    term.Dec(measure_raw(500))
PRI measure_raw(period) : raw_weight | timeref
  raw_weight := 0
  repeat period
    ' Reset, and wait for input to go high. This is its idle state.
    OUTA[PIN_SCALE_OUTPUT]~
    DIRA[PIN_SCALE_OUTPUT]~~
    waitpne(0, constant(|< PIN_SCALE_INPUT), INA)
    ' Turn off the 'reset' output. This starts integrating
    ' the pressure. When the analog integrator reaches a threshold,
    ' our input pin goes high. Time this.
    timeref := cnt
    OUTA[PIN_SCALE_OUTPUT]~~
    waitpeq(0, constant(|< PIN_SCALE_INPUT), INA)
    raw_weight += cnt - timeref

And that’s all it takes! I’m looking forward to trying this with a larger grid of scales. A powerful microcontroller like the Propeller should be able to simultaneously sample and filter measurements from several scales. This proof-of-concept looks pretty promising for the kegerator project, too. With an integration time of a second or so, it can easily measure weight accurately enough to count glasses of beer ๐Ÿ™‚

P.S. ย I’m pretty sure I just spent more time writing this blog entry than I spent on the hack itself. How silly is that?

DIY Sewing Machine Retrofit

The story behind this project is a bit overcomplicated. That’s all below, if you’re interested. I made a video to explain the final product:

Back Story

This all started when I bought a sewing machine for making fabric RFID tags a little over a year ago, and started using it to make cute plushy objects. Well, as much as I like making plushy objects, I haven’t actually made very many of them since buying the machine. So, my boyfriend has been guilting me into making him a few as gifts for Christmas, birthday, valentine’s day. Naturally, being the great partner I am, this gets me thinking about ways to soup up my sewing machine first ๐Ÿ™‚

The original machine did bug me in many ways when working on fine detail work. I’m lazy and uncoordinated with a needle, so I tend to sew almost everything by machine, even when the individual stitches all have to be lined up just right. In fact, when sewing the face parts on my meat and crab plushies, I found myself sewing individual stitches by turning the flywheel by hand.

I don’t know whether more expensive sewing machines are any better, but on my cheap Singer Inspiration 4210 the stock motor is nearly unusable at slow speeds. It stalls easily, makes an awful buzzing noise, maintains an uneven speed, and delivers very little torque.

Sensors

My first experiments were to instrument the sewing machine with sensors that I could use to estimate the speed and angle of the main shaft. ย I needed some kind of absolute angle reference, plus some way of counting how far the shaft has traveled. For the angle reference, I found a really handy place to mount a photo-interrupter sensor. This cam is part of the mechanism that advances the machine’s feed dogs. It conveniently moves this metal bar back and forth once per revolution of the shaft.

Photo-interrupter mounted

For sensing the shaft speed accurately, my preferred solution would have been a high-resolution encoder wheel attached to the motor or the main shaft. But that would, at the very least, involve making a rotary encoder disc and attaching it somehow to one of the sewing machine’s moving parts. I wanted to avoid messing with the machine’s moving parts as much as possible, so I looked for non-contact solutions. I noticed that, with a little signal conditioning, an IR reflection sensor works pretty well for counting teeth on the machine’s drive belt. After switching motors, I modified this to sense teeth on the motor’s sprocket instead, but the same signal conditioning circuit works in either case. The signal conditioner is an dual op-amp configured as an amplifier, bandpass filter, and comparator with hysteresis.

Optical tachometer

Lastly, there’s the most important sensor: the foot pedal! I wanted to keep the original foot pedal feel, but use it as a generic input device for the microcontroller. So, I removed all electronic parts other than the variable resistor itself, and connected that to a 1/8″ jack. With a little modification, the jack fit into the same hole that was originally used for the mains cord.

Pedal after modification

Induction Motors Suck

This is where the project got a bit out of hand and I started making wrong turns. At first, I was hoping it would be possible to implement smooth closed-loop control by using the original motor and a simple triac-based speed controller for the motor. This seemed straightforward enough. But I didn’t have all of the parts on hand to do a normal optotriac + triac based driver circuit. So I went shopping at HSC. No optotriac, but there were some solid state relays. Alas, after I got them home and looked up the data sheets, it turns out they are the zero-crossing switching variety. Useless for speed control. So, back to the drawing board. No optotriacs on hand. Well, I could move the opto-isolation, putting the microcontroller on a line-powered circuit, and opto-isolating the serial port instead. But that sounded really annoying to debug safely, especially for me without an isolation transformer or variac. But that would require a low-voltage power supply on the mains ย side of the optoisolator anyway, and if I had to go to that trouble I might as well just use a transistor to switch on the triac…

So I started rummaging through my junk bins again, and I found an old X10 lamp module. This must have a triac in it, I thought. It won’t have an optoisolator, since X10’s cheap circuits never bother with mains isolation. But it might have a power supply and zero-crossing circuit I could use. So I find a handy LM465 schematic online, and I start paring down the circuit into just a bare-bones triac driver, zero crossing detector, and +15V power supply. I got pretty far along on this triac-based speed controller before I switched tactics:

Old triac-based controller (closeup)

I was experimenting with closed-loop servo control using this triac controller, but the results were pretty uninspiring. With a triac, you can only change speeds as fast as twice your AC power frequency. And a 120 Hz control loop just isn’t tight enough to keep the sewing machine operating smoothly at low speeds. The motor’s lousy torque at these speeds certainly doesn’t help.

I also had lots of trouble with EMI in this design. With all the parts strewn about my desk and electrically isolated but not RF shielded, my microcontroller would randomly reset after the motor ran for a few seconds or so. I first saw this with my trusty Propeller. I tried switching to an AVR Butterfly, half to try and avoid the EMI, half to have its LCD and joystick as a user interface. But, no luck.

I was curious how they solve this problem in industry. Servo motors are pretty common in industrial automation, and surely you must need a fancier way to control the speed of a large motor in order to build a heavy-duty servo. Well, it seems that there are two solutions:

  • Just use a DC motor instead of AC. This is more expensive, but it’s simple and until recently it was the only option.
  • Variable-frequency drive. You still use an AC motor, but now you use an AC-to-DC power supply plus a DC-to-AC inverter to control the frequency of the motor’s power supply. With an induction motor, this controls the speed.

VFD seems quite cool, and I was really close to attempting to build a simple VFD controller using parts from a dead UPS. But then my better senses caught up with me…

So, I was about to settle for this mediocrity and finish off my triac-based controller with some buttons and mounting hardware from HSC, when I randomly happened upon the perfect DC motor. I didn’t know it was perfect at the time, but I had a hunch. As soon as I got it home and sat it next to the original motor, I knew.

New motor, old motor

I was pretty lucky. The speed range was good, the sprocket had the same pitch, and it had plenty of torque at low speeds. The only problem: It’s just barely too large to fit inside the sewing machine cabinet. So, I had to improvise the mounting a bit. I ended up slicing off the bottom panel of the sewing machine,ย bolting its frame to some scrap pressboard, and mounting the motor using a hacky arrangement of pressboard scraps, screws, and zip ties.

I started out building a simple MOSFET speed controller for the motor, since I’d never used a MOSFET to control an inductive load before. But after spending an hour or two trying to squash transients and convince my FETs to switch at a high enough frequency, I figured I’d had enough pain for one week. I had a spare LMD18200 chip with this project’s name on it.

The LMD18200 is an amazingly versatile and robust little chip. I used it for my laser projector project a while back. It was really overkill for that, but it’s about right for this sewing machine’s beefy new motor. I needed a pretty heavy duty motor drive capacitor too, so I ended up mounting the LMD18200, capacitor, and DC-DC converter in a small metal box for safety reasons. If the capacitor fails, I’d prefer not to have burning hot electrolyte and shrapnel all over my face.

Motor drive and power supply box

Future work?

Enough rambling for now. And I guess I should stop hacking my sewing machine, and start sewing cute things ๐Ÿ™‚

I did leave plenty of room in this build for later expansion. I’d like to add some kind of user interface for switching sewing modes. Right now I’m using the USB port for that, but a little LCD with a rotary encoder knob would be just swell. I’ve also thought of other ways to automate the sewing machine to make common tasks easier. For example, it would be useful to have a mode that automatically lifts the presser foot between stitches in single-stitch mode. I already found a good place to mount an RC servo motor for that.

And then there’s the idea of building a CNC embroidery machine around this, using Lego Mindstorms to make the cartesian robot…

Links

Temporal Hex Dump

After building some hardware to trace and inject data on the Nintendo DSi’s RAM bus, it became obvious pretty fast that there’s a lot of data there, and (as far as I know) no good tools for analyzing these sorts of logs.

The RAM tracer has already given us a lot of insight into how the DSi works by virtue of letting us inspect the boot process, the inter-processor communication, and most of the code that runs on the system. But all of that knowledge comes in an indirect way, from using the RAM tracer as a platform to run other experiments. I’ve been interested in figuring out whether there’s a way to use the RAM trace itself to help understand a system’s dynamic behaviour.

The RAM is on a packet-oriented bus, so it would make sense to have a tool that looks kind of like a packet-based protocol analyzer. Think Wireshark, but for memory.

But there are also a lot of complex patterns that show up over time. As the DS loads a file, or initializes itself, or renders frame after frame of a UI, there are obvious patterns that emerge. So it also might make sense to have a visual tool, like vusb-analyzer.

Unfortunately, both of these approaches ignore the spatial organization of memory. The bus is a stream of packets that say ‘read’ or ‘write’, but the contents of RAM as a whole is more like a file that’s changing over time. Like in a version control system.

So the tool I’ve been imagining is kind of a hybrid of these. It would have a graphical timeline that helps you visually navigate through large datasets and identify timing patterns. It would have a packet-by-packet listing of the reads and writes. And most importantly, it would be a hex dump tool. But instead of showing a hex dump of a static file, it would be a two-dimensional hex dump. The hex dump shows space, but you can also scrub forward or backward in time, and watch the hex dump change. The hex dump could be annotated with colors, to show which data is about to change, or which data recently changed. You could right click on a byte, and see hyperlinks to the memory transactions that are responsible for that byte’s previous and next values.

As far as I know, nobody’s written a tool like this. So I have no idea how useful it will actually be for reverse engineering or performance optimization, but it seems like a promising experiment at least. So far I’ve been working on an indexing and caching infrastructure to make it possible to interactively browse these huge memory dumps, and I’ve been working on the visual timeline widget. Here’s a quick screencast:

The top section shows read/write/zero activity binned by address, with each vertical pixel representing about 64 kB. The horizontal axis is time, with continuous zooming. The bottom section of the graph shows bandwidth, color-coded according to read/write/zero. Blue pixels are reads, reds are write, and orange is a write of a zero byte.

This log file is about a gigabyte of raw data, or about 2 minutes of wallclock time. It shows the Opera browser on the Nintendo DSi loading a very large web page, then crashing. You can see its heap growing, and you can watch the memory access patterns of code, data, and inter-processor communication.

There’s a lot of room for improvement, but I’m optimistic that this will be at least a useful tool for understanding the DSi, and maybe even a more generally applicable tool for reverse engineering and optimization.

As usual, the source is in svn if anyone’s interested. It’s implemented with C++, wxWidgets, sqlite3, and Boost. I’ve only tested it on Linux, but it “should” be portable.

DSi RAM tracing

It seems like a lot of people have been seeing my Flickr photostream and wondering what I must be up to- especially after my photos got linked on hackaday and reddit. Well, I’ve been meaning to write a detailed blog post explaining it all- but I keep running out of time. So I guess a “short” blog post is better than nothing.

The executive summary is that I’ve been working on making it possible to run homebrew games on the DSi. If you’ve used The Homebrew Channel on the Wii, you know what I’m talking about- we’d basically like to have the same thing for the DSi. And as it turns out, the DSi has a lot in common with the Wii.

I haven’t been working on this project alone. I’ve been collaborating with the excellent software and hardware engineers in Team Twiizers, the group responsible for The Homebrew Channel. Bushing has written a couple blog posts about our DSi efforts so far: one on the RAM tracing effort in general, and one with a sample trace.

My role in this project lately has been building hardware and software for a tool which is effectively a low-level CPU debugger for the DSi. It attaches to the RAM bus between the RAM and CPU, it’s capable of tracing all traffic in ‘real-time’ (after slowing down the system clock so the required bandwidth fits in USB 2.0), and just this week I got RAM injection working. The hardware interposes on one of the chip select signals between the CPU and RAM. If an address floats by that we want to patch, the hardware can quickly disable the real RAM chip and drive new data onto the bus as the CPU continues to read. It’s a very effective technique, and my hardware has a pretty capable system for storing and retrieving up to 16 kB of patch data now.

So why is all the complex hardware needed? Well, we hit two big dead-ends:

  • Several of us managed to run code from within a DSi-enhanced game using modified save files, but most of the interesting hardware on the DSi (like the SD card slot, and the internal flash memory) is disabled when these games are running. The earlier Team Twiizers Classic Word Games hack, WinterMute’s cookhack, and my own cookinject all suffer from this problem.
  • I’ve been able to read and write flash memory for a while. This isn’t as interesting as it may sound, since nearly all of the flash is encrypted. However, by running a lot of tests where we modified or compared the encrypted data, we were still able to gain a lot of knowledge about the layout of the flash memory, and some information about how the system boots.

What we’d really like to do is understand more about how the console’s main menu works, and how software is installed and loaded on the DSi. The best way to do this seemed to be RAM tracing. It required an FPGA and a lot of crazy soldering under a microscope, but now it’s working and we’re well on our way to unlocking the secrets of DSi homebrew.

If you’re interested in following our efforts to make homebrew possible on the DSi, definitely subscribe to Bushing’s blog at hackmii.com. He understands the Wii (and by extension, the DSi) better than I ever will, and he’s great at writing about it.

I have a Flickr set with lots more photos, but these are two of my favorite. The first is a photo of the entire setup as it’s currently configured. The second is a picture of the craziest of the microscopic solder joints in this project. This is where I separated the chip-select signal I mentioned above, giving the FPGA the ability to sit between the CPU and RAM. The trace I’m tapping into is buried under four other PCB layers. For a sense of scale, the orange enameled wire is 32 AWG, or about 0.2mm in diameter. Normal 30 AWG wire-wrapping wire is actually only the third smallest size of wire I’ve been using in this project ๐Ÿ™‚

Debugging setup with new FPGA

Via excavation closeup

If you’re interested in the C and Verilog source code, it’s in Subversion as usual.

Robot Odyssey DS: First screenshots

This is nowhere near ready for prime-time, but:

img_0635.jpg

img_0639.jpg

Yep, it’s Robot Odyssey for the Nintendo DS. I literally just got this working yesterday, so please don’t ask for any precompiled binaries. If you don’t already know where the source code is, you really don’t want to see it ๐Ÿ™‚

Before you ask, this is not a general-purpose DOS emulator for the DS. It’s actually a static binary translator which does most of the work in porting a DOS game to the DS, but there’s still an awful lot of manual intervention required. I only really developed the translator with Robot Odyssey in mind, so there are sure to be features missing that you’d need in order to use it with other games.

My intent is to turn this into a real port of Robot Odyssey to the DS, not just an emulation. In particular, I’d like to re-do the load/save game UI to support timestamps and thumbnails, and I’d like a soldering mode that makes use of the DS’s touchscreen.

Announcing the VMware SVGA Device Developer Kit

Over the weekend, I finally had time to release another work-related open source project: the VMware SVGA Device Developer Kit. It’s a set of documentation and example code for the virtual graphics card that’s present in all VMware virtual machines. The examples run on the (virtual) bare metal, so it’s a really easy way to experiment with low-level graphics driver programming.

Robot Odyssey Mouse Hack 1

Yesterday I spent some more time reverse engineering Robot Odyssey. This was a great game, and it’s kind of a nostalgic pleasure for me to read and figure out all of this old 16-bit assembly. So far I’ve reverse engineered nearly all of the drawing code, big chunks of the world file format, and most of the code that’s responsible for moving around objects on the screen.

So, I thought I’d try manipulating some of that data. I extended my existing binary patch to add even more code to the game’s per-frame blit function. It sets up the mouse using DOS Int 33h, and lets you manipulate the game’s table of sprite locations by dragging objects with the mouse.

I took a video to show the results. It’s still obviously a hack, but it may actually be kind of useful for assembling circuits more quickly.

The source code is available, but it’s a bit rough. This patch is getting kind of unwieldy in its current state, and I think my next step will be coming up with a better tool for doing these kinds of patches. I’m thinking either:

  • A pre/post-processor for NASM, which has binary patching oriented features.It would use signatures (byte mask + md5sum) to identify interesting code and data regions in the original binary, and allow you to replace or invoke snippets of code in the original binary using this mechanism. This should make it easier to do very invasive patches which can apply against slightly different versions of a game.
  • Or, scripting support for DOSBox.This could be a lot like the Lua support in FCEUX which made Super Mario Drag & Drop possible. As much as I like the idea of self-contained binary patches that operate in the same environment the game itself runs in, a Python plugin interface for DOSBox could be extremely powerful. Imagine a real-time level editor, or various kinds of real-time memory comparison tools…

Open source extra-sensitive high resolution TED receiver

Previously on the bloggy blog, I posted a few of my projects related to home data acquisition and to The Energy Detective (TED), a whole-house power measurement device. I made a set of homebrew wireless temperature sensors that display graphs on a digital picture frame, I reverse engineered the TED protocol, built a small self-contained open source TED receiver, and used that design to make a nifty clock.

So, I wanted to take the next step and set up real-time power usage graphing alongside the temperature graphs. The only problem: My sensor receivers are on a different power line phase than the TED. I’d need a TED receiver that can deal with all of the noise that switching power supplies put out, and receive weak TED signals that have been coupled across phases by the utility’s pole transformer. There were probably easier ways to solve this problem, but it was a good excuse to get more experience with analog electronics ๐Ÿ™‚

The end result was this cute little doodad:

Features:

  • Isolated power supplies for the host computer, receiver circuitry, and the power line signal itself. Separate voltage regulators for analog and digital.
  • High-Q LC filter, centered at 125 kHz.
  • Dual outputs: RS-232 serial and USB (Prolific USB-serial chip)
  • Generates human-readable text at 9600 baud:
    HC=245 KW=001.347 V=121.228 CNT=033
  • Decodes packets with up to 1 watt / 1 millivolt precision!
  • Last but not least, an oh-so-cute power/status LED which glows dimly to indicate power, and flashes brightly when a packet is received.

With all of this precision, the resulting graphs look pretty decent. Here are power and voltage graphs, for the same time period. You can certainly see the voltage dips when my refrigerator or heater fan kick on, but you can also see some loads on the voltage graph that don’t show up on the power graph. These are probably the neighbor’s appliances.

The circuit design is pretty straightforward, and it should be pretty easy to build for anyone an AVR programmer and some experience with hobbyist electronics. Inside the box the mains voltage is split into two 9V AC transformers: one for power, and one for data. The power transformer’s output is rectified, and the unregulated voltage is diverted to two 7805 regulators, one for the microcontroller and one for the amplifier. The amplifier is very sensitive to noise, and it helps to have some isolation from all the high frequency harmonics that a microcontroller will toss into its power supply.

I built the prototype on a piece of stripboard in a grounded aluminum box. From left to right: MCP6292 dual op-amp and all associated passives, power supply, ATtiny85 microcontroller, and some transistors to drive the LED brightness control circuit and the RS-232 output.

The analog front-end starts with a high-pass filter which cuts out nearly all of the 60 Hz AC power, leaving a manageable signal level. This goes through some clamping diodes, to protect the op-amp input from transients, then through a first amplification stage with a gain of about 68. It’s important that this pre-amplifier is non-inverting, to avoid oscillation. This then goes through an LC bandpass filter, and another amplification stage with a gain of about 31.

With these op-amps, you could achieve higher gains (around 80), but this is all I needed. Your mileage may vary. If you want variable gain control, try replacing the 3.3k resistor at the second op-amp’s inverting input with a multi-turn 5k trimmer pot. More ambitious readers may even want to design an AGC circuit. After the second gain stage, a final low-pass filter is very important in order to remove transients that can cause false transitions on the microcontroller’s input. The microcontroller finally gets a filtered and amplified signal. It proceeds to do the demodulation and decoding in software.

I apologize for the crude hand-drawn schematic. There are more pictures on Flickr, and software/firmware in Subversion. Happy hacking!

Wireless temperature picture frame mashup

IMG_0567

This is the latest geeky addition to our home decor. It’s a Kodak W820 digital picture frame, showing a graph of real-time temperature data collected from around the house: upstairs and downstairs, garage, outdoors, and even inside the refrigerator.

More photos on Flickr, implementation details below…

Temperature Sensors

Most of my friends probably know that back in 2004, when I was still in college, I built a set of wireless temperature sensors. Each one is an Altoids tin containing a 9V battery, a Dallas 1-wire temperature sensor, PIC microcontroller, and a little 315 MHz AM radio transmitter. I built several of these indoor wireless sensors, plus one outdoor sensor which I built out of PVC pipe.

indoor_therm outdoor_mounted Dallas 1-wire Wireless Temperature Sensor

The PIC spends most of its time sleeping, but every 20 seconds or so it wakes up to read the current temperature from the 1-wire sensor. Most of the indoor sensors have the 1-wire temperature probe soldered to the side of the Altoids tin, for the best thermal conductivity. The refrigerator sensor has a length of 30-gauge wire that leads the 1-wire sensor itself into the fridge.

Every couple of minutes, each sensor transmits a burst of packets back to the base station. The base station is another piece of custom hardware: a matching AM radio receiver, some LEDs, and a TUSB3210 microcontroller to do protocol decoding and to interface back to a server machine over USB. In this case, the host machine is a little NSLU2 embedded Linux box which also acts as our home network’s file server.

NSLU2 and wireless temperature receiver

As usual, microcontroller firmware for the transmitter and receiver is open source.

Software

The software running on the server machine has had a rough history. My original implementation was ridiculously complicated: The receiver unit connected to an NSLU2 embedded Linux box over USB. That machine ran a daemon, written in C, which listened for packets over USB and stored their contents in a remote MySQL database. The MySQL database was running on a more powerful server (a 1 GHz Athlon at the time) which had plenty of disk space. That server also ran a web application using mod_python, which pulled data from MySQL, generated graphs on demand using rrdtool, and generally looked really pretty.

My reasons were mostly historical. I wanted to save all of the temperature data (for another project I had at the time), so instead of sending data directly to a lossy RRD file, I just used rrdtool as a cache for the data I was about to graph. As you can imagine, if the cache ever had to be rebuilt, the server would come crashing to its knees. This implementation was plagued with performance and reliability issues.

So, I recently reimplemented a simpler server software solution. I hacked up the C daemon so that instead of writing to a MySQL database, it forks off an rrdtool process to store the data directly into an RRD database. Instead of generating graphs on-demand, I have a small update-graphs shell script which uses rrdtool to generate all of the graphs. This scripts is run from cron every 5 minutes. The resulting graphs aren’t nearly as intricate as the ones that my mod_python app used to generate, but anything looks pretty if you antialias it ๐Ÿ˜‰

The digital picture frame

This frame is a Kodak W820, an amazingly featureful little gadget that I picked up at the local Fry’s for $180. It has an very pretty 8″ 800×480 display and a rather unique touch-based user interface. It also does a pretty ridiculously good job at playing video, considering it’s a picture frame.

But anyway, the real reason to buy this frame is for its Wi-fi connectivity. If you connect it to your network, you get a range of useful and “useful” services:

  • The frame runs its own HTTP server on port 80, with a web interface you can use for managing settings. You can’t upload pictures via this interface, but it does mean that you can configure the picture frame entirely without using Kodak’s silly Windows software.
  • It’s a uPnP media server and a client. The software that comes with it uses uPnP to browse an upload/download files on the frame’s internal memory or memory card, and the frame itself can use uPnP to stream images from your PC. This is a really interesting feature that could be exploited for more dynamic applications…
  • It has a Flickr client. Yes, the frame itself actually speaks the Flickr API.
  • There’s some fancy-pants Kodak online service, which looks like it’s probably little more than an RSS feed in disguise.
  • And best of all, you can give it custom RSS feeds. Like, say, real-time temperature graphs!

The only snag I hit in setting this up was in trying to keep the frame from caching old versions of the temperature graph. It seems to ignore HTTP cache control headers, and the cache seems to be able to hold quite a nontrivial amount of image data!

The best solution I’ve found so far: Use the RSS <ttl> tag to force the frame to reload the RSS feed itself pretty frequently. Then, in my update-graphs script, I dynamically generate an RSS file which includes a timestamp in the URL and GUID for each image. This seems to do the trick.

What next?

I’m really interested in graphing my home power usage, using a receiver circuit based on the one I built for The Kilowatt Clock. I’m currently waiting for some parts from Digi-key, but I’ll definitely blog about this when it’s done.

If you’re at all interested in displaying real-time stats around the home or office, I’d definitely encourage you to play with this picture frame. It has some great hacking potential, and I’m really excited to see what kinds of uses others come up with.

Virtual USB Analyzer

From late 2005 to early 2007, I worked on the USB virtualization stack at VMware. We ran into all sorts of gnarly bugs, many of which were very hard to reproduce or which required access to esoteric or expensive hardware. To help with debugging problems both internally and with customers in the field, we added logging support to our virtual USB stack. Starting with VMware Workstation 5.5, if you set the right hidden config option we’d start dumping the contents of all USB packets to a log. It was a USB sniffer (like USB Snoopy), but built into the virtual hardware.

To make it easier to analyze the resulting logs, I started working on a GUI tool that could navigate through these giant log files. This tool proved to be really useful within our team at VMware, and we’d often ask customers on the beta forums to generate log files that we could analyze. I called this tool vusb-analyzer.

Well, it’s been a while, but I’m proud to now have the opportunity to release vusb-analyzer as open source software under the MIT license. This isn’t just a code dump- I removed the tool from our internal repository today, and all future development will occur in the open, in a Subversion repository on Source Forge.

Currently, vusb-analyzer is most useful for analyzing logs captured by VMware products. Indeed, this is a convenient way to debug USB drivers. You can attach your USB device to VMware Workstation, VMware Fusion, or the free-as-in-beer VMware Player, and it can transparently save a plaintext log of all USB packets that pass through. Debugging a driver in a VM is really convenient, and I find it quite useful, but I understand it’s not for everybody. If you already have a favorite USB sniffer tool, it’s easy to extend vusb-analyzer with a log format plugin so it can read other formats. We already did this once, to add support for the logs generated by our favorite hardware USB analyzers.

I hope vusb-analyzer turns out to be useful for the open source community, particularly to those who are working on Linux device drivers. To get started, visit the project’s web site:

http://vusb-analyzer.sourceforge.net

Besides the usual introduction and download links, there is also a detailed tutorial with lots of shiny screenshots ๐Ÿ™‚