Friday, May 27, 2011

Propeller ADS7888 ADC driver

My Propeller Schmartboard and ADS7888 analog to digital converter had been collecting dust long enough.

And I was sick of the slow frame rate I was getting from my Game Boy Camera running off an Arduino. I thought a fast ADC and a more powerful MCU might help that. These were my good excuses to dive into the world of Propeller and write a driver object in Propeller Assembly.

Propeller, ADC, and lots of wires = fun
The Interface
The ADS7888 interface consists of an active low chip select (!CS), serial clock (SCLK) and serial data out (SDO). Dropping !CS initiates ADC conversion and clocks out the first of 4 leading 0's. The remaining three 0's followed by eight data bits with MSB first, are all clocked out just after the falling edge of SCLK. Raise !CS after the 12th bit for high throughput mode, and start all over again after a brief wait time.
Timing diagram from ADS7888 datasheet, 12-clock frame
The Process
So all I had to do is raise and lower pins and shift in data at the right times.  And the Propeller makes this really easy, thanks to deterministic timing. No interrupts and each instruction takes 4 clock cycles (with few exceptions that you can avoid or plan around).  So you can sync and run multiple cogs in lockstep.

I started by sketching out the instructions in Spin, then converting to assembly, learning on the fly. Propeller assembly strikes me as much easier to learn than others I've tried (6502, x86, VAX, ...)  I focused initially on just getting the right pins up and down in the right sequence. Then coded in the serial input. Then I added NOP instructions where necessary to ensure consistent SCLK periods throughout.

Tuning the Assembly Code
The total SCLK period was pretty long at this stage in development. Data acquisition is pretty tightly constrained by the Game Boy Cam's clock period of 2000ns so it was time to tune the code.

After finding the longest loop (serial shift in), I was able to reduce the number of instructions to 6 total (below) and removed NOPs elsewhere to reduce the SCLK period throughout.

:loop2        test sdo, ina wz ' SCLK down, data valid after 7ns
              shl data, #1     ' shift data left 1 bit
if_nz         or data, #%01    ' stick the next bit into data (or don't)
              nop              ' SCLK up
              sub j, #1 wz     ' deterministic timing
if_nz         jmp #:loop2      ' deterministic timing

I then moved initialization code into NOP slots later in the code to reduce setup time shortening the overall acquisition period.

Next I split the SCLK signal generation statements out to run in a separate cog, synchronizing with !CS using WAITPNE.

DAT RunClock
              org 0
clock         or dira, sclk1
mainloop      or outa, sclk1
              waitpne cs1, cs1   ' sync on !CS down
:clkloop      andn outa, sclk1   ' SCLK up
              test cs1, ina wz   ' if !CS high
              nop
              or outa, sclk1     ' SCLK down
if_nz         jmp #mainloop      ' if !CS high
              jmp #:clkloop
              
cs1     long  |< 3 ' ADS7888 !CS pin
sclk1   long  |< 5 ' ADS7888 SCLK pin

This shortened the SCLK period by two instructions yielding an acquisition period of about 975ns.  That leaves 1025ns of the Game Boy Camera's clock period free.  At 80MHz, that's 12.5ns per instruction, or 82 instructions per XCK period to store the pixel data in shared system memory, and maybe do something else with the data. In the same cog that's driving the camera, that is.

Meanwhile, several other cogs will be available, each with a full 2000ns (160 instructions) for each of the 15744 pixels, plus some idle time between frames to do some interesting processing. I suspect I'll be able to do some cool image processing as a result. Especially since the Game Boy Camera does on-chip edge detection.

I think it's safe to say I'll be able to do more than just detect candle flames by the time I'm finished, here. Including, I hope, obstacle avoidance, line following, even sidewalk/lane following. Who knows?

Source code is here.

Troubleshooting
I extensively used my trusty Hitachi V-1050F oscilloscope to check the consistency of the timing, and the timing of SCLK versus !CS.  The "B Display" feature magnifies and displays a small section of a longer waveform period. I could scroll through a long trace from beginning to end to ensure consistent timing between SCLK and !CS.

"B Display" shows a magnified window of a long trace

I hooked up a potentiometer as a voltage divider connected to VIN so I could check readings. The scope let me see the serial data coming out of the ADC, and I set up a wrapper program to send the ADC result over serial to the PC. I could verify that the serial data sent by the ADC matched the value read in by the software. Doing this caught a timing bug that dropped the LSB of the result.

%1001011 = 0x4b

I may double check the timing on all three pins at once with my HP 1650A logic analyzer if I can clear off my workspace.

Next Steps
Time to write a Propeller driver for the Game Boy Camera. I may have to combine the camera and ADC driver code for efficiency. My old digital logic text from college suggests that a ROM-based state machine might be the most efficient way to run the camera and ADC together. If I do that, it'll make a fun article. I'm considering experimenting with a parallel-interface ADC to further boost performance.

Friday, May 20, 2011

AVC Bot sees!

I'm still bummed about the result at the 2011 AVC (speakin of which, Sparkfun posted a video). Even with the head start I gave myself I guess it was just too much to tackle.

You may recall that the barrel obstacles in the 2011 Sparkfun AVC were red. I had been hoping that would be the case as I'd hoped all along to use computer vision for obstacle avoidance.

CMUcam test screen capture
Taking a lesson from my experiences with Pokey V2.0, even simple vision systems can simplify problems dramatically. Such as finding a candle flame. Or a giant red barrel so you know what direction to steer.

George M., one of my pals from SHARC, kindly loaned me a BOE-Bot CMUcam v1 and it was time to learn how it worked, interface it to the mbed, and then work out an algorithm to avoid giant red blobs in the robot's path.

I was able to get all the interfacing done in time, but ran into other issues. Here's the rundown.

Step 1: CMUcam Serial Interface

The CMUcam uses a simple, human-readable serial interface. You can use it from a terminal program like Termite. Or you can use their beta Java desktop application to do frame dumps (see pic, above right) and control other features of the camera.

Commands are terminated with a carriage return ('\r' for C/C++ people) and include things like RS for reset, TC for track color, MM for setting middle mass mode on/off, and myriad other commands.

Step 2: Arduino Control

The mbed on Data Bus has finally run out of serial peripherals: iGPS-500, AHRS, and the third USART is used for I2C instead of serial. That's for the compass

Anyway, with little time left, I decided to quickly make a Serial to I2C bridge with an Arduino-compatible ATmega328P. Controlling the camera over serial wasn't too difficult. I used NewSoftSerial for the camera and added an FTDI header for programming/debugging. I added several debugging features intended to save my bacon on race day.




From the PC I can monitor I2C activity, query the latest bounding box info, or even bridge the PC to the camera and control it with the CMUcam java app, all in-circuit and on-robot. It's really pretty neato.

The Arduino tells the camera to reset and track red blobs. It reads the reported x and y coordinates and sticks those in memory for access from I2C or serial.

There's also a watchdog that resets and reconfigures the camera if it stop spitting out color tracking packets for too long. It seems to work pretty well. All told, I'm pretty happy with how it all turned out.

Step 3: I2C Communication

On Arduino, I have had bad luck getting I2C to work. It's easier on the mbed, to be sure. The coding seems more intuitive to me than it did on the Arduino. So what better course of action than trying to get the two talking to each other?

Data Bus' mbed talking to breadboard Arduino talking to CMUcam
I had to refresh my knowledge of I2C protocol. I re-read the mbed Handbook on I2C and the Arduino Wire Library documentation. My first attempt failed miserably. Reluctantly, out came the ancient logic analyzer.

It was unhelpful until I remembered I was seeing a lot of data from the compass communication on the same I2C bus. Disabling that code helped. Then I read the part in the I2C tutorial that device addressing is 7-bit, with an 8th bit added as a read/write indicator.

On the Arduino I simply call Wire.begin(7), where 7 is the Arduino's I2C address. Then call Wire.onRequest() specifying a handler function that spits back 4 bytes, x1, y1, x2, and y2 for the bounding box.

I found it easiest on the mbed to use the "raw" I2C library's start(), write(), read(), stop() methods and manually setting the address. Take the I2C address, left shift once, and set bit 0 to indicate a read operation. Then read four bytes. Like this:

        cam.start();
        data[0] = (0x7<<1 | 0x01); // send address + !write = 1
        cam.write(data[0]);              // send address
        data[0] = cam.read(1);
        data[1] = cam.read(1);
        data[2] = cam.read(1);
        data[3] = cam.read(0);           // don't ack the last byte
        cam.stop();

Eureka, it works!

The logic analyzer shows the camera tracking a small red object on my desk.


Here's some screenshots of the serial interfaces I have going simultaneously. The mbed is in "instrument check" mode, reading and displaying sensor values.  You can see the box coordinates reported here.


The Arduino is in "standard" mode, after having been in "monitor" mode displaying i2c request events. The "q" command queries the current bounding box values; the same data the mbed's I2C query receives.


Step 4: The Hardware

The schematic and board are pretty simple. I'm basically copying the Solarbotics Ardweeny schematic, but using some SMD passives to keep the board uncluttered. The one through-hole resistor is convenient for single-layer routing.

Step 5: The Algorithm

In general the idea is to detect a big red object a few meters away and begin steering the robot so that the red blob isn't in the center of the image. The algorithm will have to pick a direction and either override, subsume, or trick the navigation steering algorithm to turn the robot.

Of course how far does the robot steer left or right? Imaginary parallel lines in front of the robot describe its track width. The robot, taking a picture, would see these lines converge to the vanishing point at the horizon.

I'll have to figure out what pixels these lines would occupy, and then steer the robot until the red blobs are outside of these track width lines (plus some safety margin).

Epilogue

I should've tested this right away and saved my time for fixing the navigation code.  For some reason every time the Arduino and CMUCam are powered up, the GPS signals tanked. The signals drop in strength by 30-50dB! In other words, the GPS fix goes from 9 satellites to 3 instantly. I ran out of time to investigate EMI/RFI as a possible cause. So Data Bus wasn't able to see red or anything else on race day. Maybe next year.

Friday, May 13, 2011

Choosing a Microcontroller

Oooo, lookit all the cool toys!
In case it helps you, I wanted to share my experiences considering several microcontrollers as the brain of my Sparkfun AVC 2011 and 3rd place winning 2012 robot, Data Bus.

Each project is different with a unique set of goals. The key is to think about the goals and how well each option meets those goals. For example...

Goals

My primary goals were to save development time, and to support whatever level of computation required by the robot, and to provide interface flexibility in connecting myriad yet-to-be-chosen sensors. I wanted to keep costs reasonable. Sub $100 or ideally sub $50.

Options

I considered several options for the robot
  • Arduino-compatible: diy pcb, Arduino IDE; super-cheap!
  • An Arduino-flavored AVR XMEGA type thing
  • The Maple, ARM Cortex M3 from Leaf Labs; Arduino-like IDE
  • The mbed LPC1768, ARM Cortex M3 from NXP: online; cloud-based IDE
  • Blueboard LPC1768-H, another Cortex M3; cheap!
  • Parallax Propeller, like my eeZee Propeller, multicore deterministic
  • LPCXpresso, LPC1769, Cortex M3, cheap! (considered in 2012)
Other options I didn't consider (or which weren't available)
Library support

Having a platform with good library support was crucial to saving time. I didn't want to have to develop a lot of libraries.

Best: Arduino is a good choice as it has such a massive following. Most of the common sensors have something written out there somewhere.

Great: Initially the mbed seemed like it would have excellent library support. In fact I ended up writing and publishing most of the drivers myself, but I was easily able to adapt code from Arduino in a couple instances, and use a few existing libraries in other cases. It worked out ok. Device support is better since I originally wrote this.

Good: The Propeller generally has good community support with libraries. I would've had to write many myself and porting code would've been harder if I used Spin. But prop-gcc has become quite popular in the last year or two. Despite the 8 cogs and 80MHz clock speed the reality of hub memory and 4 clock cycles per instruction

Ok: Leaf Labs was an unknown but it was possible that much of the Arduino library code had been or could be easily ported. My latest impression from a year or two ago is that the Arduino library implementation isn't all that optimal or complete and hadn't seen much activity in awhile.

Not sure: The Blueboard. With an LPC1768 it should be binary compatible with most of the mbed SDK (recently open sourced). Otherwise, you'd have to code nearly bare metal, using CMSIS at worst or one of the (few?) RTOS HALs out there.

Not sure: LPCXpresso is supposedly mbed compatible otherwise it's CMSIS or maybe you can find a HAL; it's the same family as LPC1768 so theoretically it should work.

IDE

The IDE has an impact on speed of development.

Good: The Arduino IDE makes for writing small code quickly. Very complex code can be done... it can get a little messy. Ability to do version control is nice and provides a little freedom for moving the development environment from system to system. (I use Subversion with Google Code hosting).

Good: The mbed IDE is more like a real IDE, or a good editor but with version control and the really nice integrated library repository. The big downside with cloud-based of course is when you're at the AVC and they have no internet connectivity then what? Well, offline compile is possible, now, with a variety of tools/IDEs. You may not see the performance of the online compiler.

Good: Propeller Tool is well-suited to SPIN and PASM and generally is set up nicely. I've used it quite a bit, I'm happy with it. It's Windows only. Brad's Spin Tool is an option. I've not played with the Simple IDE yet.

Not sure: Code Red for LPCXpresso now supports C and C++ and it is based on Eclipse which I rather like.

Not sure: Plain old Eclipse with plugins for ARM is one way to go. And maybe open source debugging tools. But that's a mountain of work I've not yet climbed.

Peripheral support

Best: The Cortex M3 has 4 serial ports, USB, CAN, multiple I2C, ethernet, and multiple SPI ports. Clearly the winner since I had I2C, two serial, and two SPI devices. I could've plugged the robot into a wireless AP and controlled it via web over WiFi had I wanted to.

Good: The XMEGA has more peripherals than Arduino so it might've been viable.

Meh: The Arduino Duemillanove, Uno, etc., based on ATmega328P are in a different (much lower) class, with only one of each peripheral. The Arduino Mega, based ATmega2560, would've provided more peripherals.

Good: With Propeller, all the peripherals (except timers/pwm/counters) are done in software. On the one hand, you can have a lot of peripherals and just what you need. On the other hand they will probably perform slower than hardware-- I2C even in PASM has delays due to hub synchornization-- and I'm finding it difficult to track down good peripheral drivers, sometimes. I had to write my own I2C master object because I couldn't find a decent one. Parallax has an online repository but it is lacking compared to mbed.org, particular Doxygen-generated documentation for object APIs.

Processing power

Best: LPCXpresso runs 120MHz and nearly 1 instruction/cycle, lots of RAM and flash. The program size is limited by Code Red (free version) but even then it's quite a bit.

Best: mbed runs 96MHz at 1 instruction/cycle which was plenty and also lots of RAM and flash with no code limits that I know of (but you might double-check). Ran software floating point with ease. Processor was underutilized even doing lots of calculations at 100Hz for my rover.

Ok: Propeller has 32K but it's hub ram and incurs major delays to read/write, but it's the only way for a PASM routine to communicate with Spin objects and Spin is too slow to do device drivers, usually. Each cog has 2K ram which is nice. The 80MHz runs 4 clocks / instruction so that's effectively about 20MIPS times 8 cogs but then you have the 7+ clock cycles for hub synchronization which slows things down.

Worst: Arduino with ATmega328P is only 20MHz (around 20MIPS) with only 32k flash and 2k RAM.  You'll have to be careful with floating point and such, but... you can still do more than you think.

Community support

The ability to find answers and solutions will dramatically speed development efforts versus having to invent the wheel all on your own.

Great: Arduino lots of community, forums, example code.

Best: mbed has quite a big community now too, with forums, cookbooks, and a code repository unlike Arduino

Ok: Propeller has a big community and forums, and while it has a code repository but I find it very difficult to search and the documentation is consistently so bad you invariably have to download and look at the source to have any idea whether the object will work for your needs.

Bad: LPCXpresso has a forum. I'm still struggling to figure out how to do anything interesting. Not impressed so far.

Summary

In short, of all the choices, the Cortex M3-based solutions were easy choices due to the massive number of peripherals and the significant computing power. The cost and completeness of the mbed solution made it my clear winner in the end. I migrated to it around January, about four months before the big competition in 2011. Since then it is one of my top tools alongside Arduino-ish stuff. I found it easy to manage 20k lines of source that drove Data Bus and I to a 3rd place in 2012 so overall, I'm very pleased and things keep getting better. With an open SDK, offline compile, and more MCUs supported every time I look, it seems like a great option.

If you think others might find this helpful, take a second and share? Thanks!