Archive

Archive for May, 2010

XBoot – Quick Start Guide (for a sweet XMega bootloader!)

So in my recent XMega wanderings,  I needed a good bootloader.  After muddling through various app notes and forum postings, I came across the culmination of what I couldn’t do on my own – XBoot!

In my defense, I’ve worked on bootloaders before.  But the errata sheet on the XMegas is longer than the list of men Princess Leia has broken the hearts of.  And I’ve become one of the many casualties of that list.  (Erm, the errata list…  awkward…)

Big thanks to Alex Forencich!  XBoot, a fantastic reincarnation of the AVR1605 app note, is open source and highly configurable bootloader, which at the time of writing is capable of UART or I2C bootloading XMega processors.  I believe his intentions are to expand both processor compatibility and protocol options, so visit the XBoot Google Code project for more info.

I’ll  be going through and explaining the options that I used, so this isn’t an exhaustive tutorial.  This guide assumes you have a working XMega development environment, AVRDude installed, and SVN (if you want to download the code this way).  WinAVR should work just fine with a few minor alterations, but I’ve only tested this on Kubuntu with the development environment described in this previous blog post.  Also, as a side note, I’ve been using XBoot with XBee Series 1 wireless modules and it works fantabulous (that’s so good, I had to come up with a new word for it).

Overview

Here’s the step-by-step big picture:

  1. Download the code.
  2. Pick a bootloader entry method.
  3. Configure communication parameters (Port/Baud Rate/I2C addressing, etc.).
  4. Compile & program XBoot onto the MCU.
  5. Send main application via XBoot and AVRDude.

Download the Code

So let’s get started.  Download the code from the XBoot download page and uncompress it, or (my preference) use SVN to download the code:

svn checkout http://avr-xboot.googlecode.com/svn/trunk/ avr-xboot

Configure XBoot

Once the code is downloaded, find the file named “xboot.h”.  Most configuration changes, if not all, will be made here.  We’ll take it one section at a time.  Line item references are from Rev12 out of the repository, but you should be able to match them up to any version.  The idea is that all available options are enabled, so comment out what you won’t be using.

// AVR1008 fixes
// Really only applicable to 256a3 rev A and B devices
//#define USE_AVR1008_EEPROM

Uncomment this line if you’ll be using an XMega256a3.  This fixes certain problems (remember Princess Leia the errata list?). I’ve heard this has hit some people but not others, even on the same silicon revision.  It may be useful for certain other chips and families – YMMV.  Check with Google if concerned.

Line 64:
// bootloader entrance
#define USE_ENTER_DELAY
//#define USE_ENTER_PIN
#define USE_ENTER_UART
//#define USE_ENTER_I2C

Here I picked the “USE_ENTER_DELAY” and “USE_ENTER_UART”, hence I commented the other two out.  Note that the “USE_ENTER_DELAY” just puts a delay at the start of the program, and isn’t mutually exclusive with the other options.  Here’s what the options mean:

  • USE_ENTER_DELAY: Delays entry by a timeout.  Timeout is set by “ENTER_BLINK_COUNT” and “ENTER_BLINK_WAIT”, but I found the default settings worked well.
  • USE_ENTER_PIN: Select this option if you want to enter the bootloader when a pin is in a certain state at power on.  Ex: You press a switch when you power cycle to enter the bootloader.  You’ll have to configure which port/pin at line 95, at the section titled “ENTER_PIN”.
  • USE_ENTER_UART: Select this option if you want to enter the bootloader if a character is received on the UART.  This requires using “USE_ENTER_DELAY” by necessity.  You’ll need to configure the UART options at line 111.
  • USE_ENTER_I2C: Select this option if you want to enter the bootloader if a byte is received through I2C.  I haven’t used this option, hence I won’t try to elaborate.

On to the next section:

Line 73:
// bootloader communication
#define USE_LED
#define USE_UART
//#define USE_I2C
//#define USE_I2C_ADDRESS_NEGOTIATION
//#define USE_ATTACH_LED

I’ll be using the UART and LED, so everything else is commented out.  If you use the LED, configure the next section also:

Line 106:
// LED
#define LED_PORT                PORTA
#define LED_PIN                 0
#define LED_INV                 1

If you’re using the UART, configure this section:

Line 111:
// UART
#define UART_BAUD_RATE                  19200
#define UART_PORT                       PORTD
#define UART_DEVICE_PORT                D1
#define UART_DEVICE                     token_paste2(USART, UART_DEVICE_PORT)
#define UART_DEVICE_RXC_ISR             token_paste3(USART, UART_DEVICE_PORT, _RXC_vect)
#define UART_DEVICE_DRE_ISR             token_paste3(USART, UART_DEVICE_PORT, _DRE_vect)
#define UART_DEVICE_TXC_ISR             token_paste3(USART, UART_DEVICE_PORT, _TXC_vect)
#define UART_TX_PIN                     PIN7_bm

Should be pretty self-explanatory.  You should only need to change UART_BAUD_RATE, UART_PORT, UART_DEVICE_PORT, and UART_TX_PIN.  If you use an exotic baud rate (non-standard and/or fast), you might want to change the settings at line 51 and select the 32MHz clock option.

That’s pretty much it for this section!

Compile & Program

This should work if you’re using AVR-GCC in Linux.  I can’t vouch for WinAVR, but it shouldn’t take much to change it.  That said, the only thing that really needs to change in the Makefile is the programmer name and the chip you’re compiling it for:

Line 42:
# MCU name
## MCU = atxmega16a4
## MCU = atxmega32a4
## MCU = atxmega64a1
## MCU = atxmega64a3
## MCU = atxmega64a4
## MCU = atxmega128a1
## MCU = atxmega128a3
## MCU = atxmega128a4
## MCU = atxmega192a1
## MCU = atxmega192a3
## MCU = atxmega256a1
## MCU = atxmega256a3b
MCU = atxmega256a3
#MCU = atxmega64a3
#MCU = atxmega128a1
#MCU = atxmega32a4

For me, I’ve been using the XMega256A3 chip.  At random, I decided to uncomment the atxmega256a3 line.  YMMV.

Line 209:
#AVRDUDE_PROGRAMMER = jtag2pdi
#AVRDUDE_PROGRAMMER = avr109
AVRDUDE_PROGRAMMER = avrispmkII

And I’m using an AVRISP mkII programmer, which is pretty cheap for an authentic Atmel programmer.  It only does PDI programming (no debugging), and needs to be updated to the latest firmware using AVR Studio (sorry, penguins – you’ll have to boot into Windows), but it does the XMega trick right nicely.

To compile and subsequently program:

$ make
$ make program

This should compile and program XBoot into the programmer.  Shazaam!  If you get any errors, feel free to leave me a comment and I’ll try to help you out.

Programming an Application Via XBoot

So now that you’ve got XBoot loaded, you can use AVRDude again to program your application to your XMega:

avrdude -p atxmega64a3 -P /dev/ttyUSB0 -c avr109 -b 19200 -U flash:w:main.hex

For those of you who may have installed Eclipse as described in previous posts, you can make Eclipse use the bootloader by:

  • Click on “Run -> Run Configurations…”
  • Right click on “C/C++ Application” on the left and select “New”
  • In the “Name:” textbox, enter “Program via XBoot”
  • In the “C/C++ Application:” textbox, enter “/usr/bin/avrdude” (or where ever it’s installed if you’re using Windows)
  • Click on the “Arguments” tab.  Enter the following line, modify to suit your needs, and then click “Apply” and “Close”
-c avr109 -p x256a3 -P /dev/ttyUSB0 -b 19200 -e -U flash:w:Debug/eclipse_project_name.hex

There you have it.  As always, if you need any help just ask in the comments below!

 

svn checkout http://avr-xboot.googlecode.com/svn/trunk/ avr-xboot-read-only

Checkers? What the … oh … Checkers!

In case you’ve noticed, my last few posts have not been about the ZephyrEye.  Not to fear – ZephyrEye is alive and well!  Boards should be readily available soon.  So for everyone out there interested in hacking together some Battlefront radar screens with your paintball/laser tag buddies, it is coming shortly.  Of course, if you can’t wait, feel free to grab the schematics and spin your own PCB ;)

So what the heck have I been posting about?  As I mentioned previously, I’m taking a Mechatronics course where we have to build a checker playing robot.  Here’s a conceptual animation for the design that my team and I came up with:

I used Blender3D to animate this video.  I’ve found with several of my robotics projects that most people get confused when I try to describe it.  By making a rough 3D sketch and animating the intended functionality, I’ve been able to talk with people much more effectively and get faster and better feedback about what will or won’t work.  It also helps me get several jumbled and mixed together concepts in my head down to a single, better defined concept.  If you’re planning on doing robotics, especially if you’re working on it from an electronics point of view, I’d highly recommend learning a 3D sketching system.  But I digress…

So this checker playing robot needs to be able to play checkers completely autonomously.  Most teams used either a stationary robotic arm or gantry style approach.  I’ve never been a big fan of either, in fact, I’m pretty enamored with the concept of small autonomous mobile robots.  A big reason for this is the ability to quickly apply swarm concepts to these robots if you build a few up, which is something I always toy around with in the back of my head but never do.

Here’s some of the primary system components and a simple description of each of them:

  • XMega256: Pretty powerful little chip.  I both appreciate this chip and its potential, and at the same time can’t believe how long the errata list is.  It’s pretty bad, but fortunately I haven’t run into too much trouble yet.  I’ll be using this for all of the checker-playing AI, computer vision, and localization tasks.  Yep, you heard me: computer vision on an AVR!
  • C328: OK, so the computer vision isn’t as hard as it could be – the COMedia C328 is a pretty easy to use (relatively speaking) UART camera.  The datasheet sucks, and it looks like it’s being discontinued.  I’m sure other similar parts will crop up soon, though.  I’ve been reading in raw 565 RGB images into the XMega RAM and finding color blobs with it.  I can also transmit a JPEG to a computer via XBee.
  • XBee: I use these for just about everything.  I usually write up a debug interface between the computer terminal and the robot so I can debug very quickly, and portably – it’s just as easy to debug and control from my desktop as it is my laptop, making presentations a lot easier.
  • Servos: We went with servos for motor control.  As my other posts have alluded, I’m using some hacked for continuous rotation, and instead of controlling position I’m controlling their speed with a standard servo signal.  To maintain balance (I didn’t want to go down the inverted pendulum road…), the bot also has a servo with a “propeller” mounted in front.  The propeller slides over checkers as the bot goes forward and backwards, but rotates when the bot turns to avoid strafing the board and moving checker pieces all over the place.
  • IR Sensors: There’s a bank of 6 IR emitter/detector pairs on the front of the bot.  These are used to detect where the bot is at on the checkerboard.    By monitoring the difference between when a left and IR detectors hit a checker square, you can also correct and maintain orientation so you don’t knock checkers all over the board.
  • Odometer Sensors: More IR sensors, this time the QRE1113 reflectance sensors.  These sensors monitor a band of alternating light/dark colors on the inside of the wheel, so every time the wheel moves a certain distance, the XMega gets a “tick” that’s worth a certain distance.
  • Chassis: A benefit of being in school, I have access to 3D printers that can take certain CAD files and actually “print” 3D objects in ABS plastic.  We used this for the chassis, which put all of our servo mounts, sensor mounts, and other typically difficult-to-make-precise-on-prototype features a lot more accurate.  It cost about $30 – not bad for what we get.

That’s the general idea.  Here’s a picture of where it’s at right now:

Here’s hoping that I get it done in time!  I don’t think it’ll get done in 12 parsecs, but that’s a measurement of space and not time anyway …

Servo Control with an XMega

I’m not going to go into a long treatise on PWM servo signals – there are plenty of references for that already.  I’d like to focus on a simple way to do a bunch of servos with fairly accurate timings on an XMega.  Also, I know this isn’t an optimal implementation – there are efficiency improvement that could be made on almost every front.  But it took me almost no time to come up with, and that says a lot.  I’m more of an idoit than I let on…

The method I’m going to line out below can drive up to 7 servos completely in interrupts.  It’ll use up your timers, but it’s easy peasy and will save you time if you don’t need all your timers for other tasks.

So, we’ve got a standard servo signal that’s composed of basically three stages:

  1. A twenty millisecond low period.
  2. A one millisecond high period.
  3. A variable high period:  To turn the servo to one extreme, force the signal low immediately.  To turn the servo to the opposite extreme, force the signal low after a full millisecond.  To turn it to some point in between, just vary the signal at this point between zero and one milliseconds.

With the advent of the XMega, the AVR series of microcontrollers now have an plethora of peripherals, notably for this article eight 16-bit timers.  EIGHT!  That’s power, baby.  For this example, I’ll only do two servos, which will require three timers.  That seems like a lot because with most ATMegas, that was about it – you only had 4 timers, and only two of those were 16-bit (and 8-bit timers == headaches

I started from App Note AVR1306, which describes the timers.  BTW, app notes are the way to become familiar with the XMegas, especially if you’re coming up from the previous AVR families.  Download the drivers along with the PDF, they’re pretty useful.  Include these in your project.  I’ve used these with only a few modifications, and they’ve worked pretty well for me so far.

Set up a global array that can be used for servo position variables:

volatile uint16_t servo[3];

Note it’s declared volatile – this is necessary for all variables you’ll be using between the main loop and an interrupt service routine.  Also note that I declared 3 spaces for two servos – on this particular one, I liked labeling the servos “Servo1”, “Servo2”, etc. instead of base zero.  Personal preference, but adding the extra byte keeps the numbering consistent between labels and array index.

Next up is the timer initialization routine.  Let’s look at it first.  The comments are fairly explanatory, and I’ll go through it a little more afterwards:

/*! \brief This function initializes timers for use as servo PWM signal drivers.
 *
 *    This function initializes timers for use as servo PWM signal drivers.
 *    It probably wouldn't hurt to improve this by making it modular at some point...
 *
 *    - TimerD0: 20ms servo timer.  This timer triggers the rest of the servo position timers.
 *    - TimerD1: 1-2ms Servo1 position timer.
 *    - TimerE0: 1-2ms Servo2 position timer.
 *
 */
void init_timers()
{
    //! TimerD0: 20ms Servo Timer
    TC_SetPeriod( &TCD0, 2500 );                            // Set period (2500 ticks = 20ms)
    TC0_SetOverflowIntLevel( &TCD0, TC_OVFINTLVL_MED_gc );  // Set Interrupt on Overflow
    TC0_ConfigClockSource( &TCD0, TC_CLKSEL_DIV256_gc );    // Set clock and prescaler (8us per tick)

    //! TimerD1: Servo1 Position Timer
    TC1_SetOverflowIntLevel( &TCD1, TC_OVFINTLVL_OFF_gc );  // Set Interrupt on Overflow, but not yet
    TC1_ConfigClockSource( &TCD1, TC_CLKSEL_DIV256_gc );    // Set clock and prescaler (8us per tick)

    //! TimerE0: Servo2 Position Timer
    TC0_SetOverflowIntLevel( &TCE0, TC_OVFINTLVL_OFF_gc );  // Set Interrupt on Overflow, but not yet
    TC0_ConfigClockSource( &TCE0, TC_CLKSEL_DIV256_gc );    // Set clock and prescaler (8us per tick)

    PMIC.CTRL |= PMIC_MEDLVLEN_bm;
    sei();
}

So, as the above code lines out, TimerD0 is the 20 millisecond timer.  Every twenty milliseconds, it fires.  When it does, it raises the servo signal and then enables TimerD1 and TimerE0, which subsequently time out the 1ms period + position offset.  These functions all come from the application note mentioned above.  The three functions used to set up TimerD0 sets the period, enables the overflow interrupt at the medium tier, and then sets the prescaler.   Pretty straightforward if you use the driver functions.

Here’s the ISR for TimerD0:

/*! \brief Timer/CounterD0 Overflow interrupt service routine
 *
 *  TimerD0 overflow interrupt service routine.
 *  Set for a 20ms period.  Sets servo output port pin, enables TCD1 which resets the pin.
 */
ISR(TCD0_OVF_vect)
{
    uint16_t period;

    /// SERVO1 Timer Enable
    period = 63 + SERVO1_OFFSET + servo[1];                // Calculate period
    SET_SERVO1;                                            // Raise the servo pin
    TC1_SetOverflowIntLevel( &TCD1, TC_OVFINTLVL_MED_gc ); // Set Interrupt on Overflow
    TC_SetPeriodBuffered( &TCD1, period);                  // Start TCD1, set period
    TC1_ConfigClockSource( &TCD1, TC_CLKSEL_DIV256_gc );   // Set clock and prescaler (8us per tick)

    /// SERVO2 Timer Enable
    period = 63 + SERVO2_OFFSET + servo[2];                // Calculate period
    SET_SERVO2;                                            // Raise the servo pin
    TC0_SetOverflowIntLevel( &TCE0, TC_OVFINTLVL_MED_gc ); // Enable timer overflow interrupt
    TC_SetPeriodBuffered( &TCE0, period);                  // Start timer, set period
    TC0_ConfigClockSource( &TCE0, TC_CLKSEL_DIV256_gc );   // Set clock and prescaler (8us per tick)
}

So, it does the following for both servos:

  • Calculates the period.  If everything were a perfect world, the constant 63 should be 125 (and a #define ;) which, with the prescaler given and a 32MHz clock, should be 1ms.  However, between natural delays in the code and the particular servos I was using, I calibrated that offset to be 63 to get the maximum range.  YMMV.
  • Raises the servo signal pin.  This macro is defined in my header file, and is pretty simple: #define SET_SERVO1 PORTD.OUTSET = PIN5_bm
  • Enables the interrupt
  • Sets the period.  You must use the TC_SetPeriodBuffered for this particular application (can’t remember why off the top of my head).
  • Set the clock source to enable the timer.

Did you notice a subtle difference between the TimerD1 and TimerE0 code?  There are two types of timers in the XMegas – Timer0’s and Timer1’s.  Hence, there are TC0_ prefixes and TC1_ prefixes that must be used for appropriate timers.  I’ll have to refer you to the datasheet, because once again I can’t remember what the difference is – it’s not relevant for this example.

Last, let’s look at the position timer ISR code:

/*! \brief Timer/CounterD1 Overflow interrupt service routine
 *
 *  Timer D1 overflow interrupt service routine.
 *  Ends the Servo1 position pulse and disables itself.
 */
ISR(TCD1_OVF_vect)
{
    CLR_SERVO1;                                            // Reset the servo pin low
    TC1_SetOverflowIntLevel( &TCD1, TC_OVFINTLVL_OFF_gc ); // Clear Interrupt on Overflow
    TC1_ConfigClockSource( &TCD1, TC_CLKSEL_OFF_gc );      // Stop clock
}

There’s not much to it:  Reset the signal low, disable the timer interrupt, and disable the timer clock source.  This all gets re-enabled in about 18-19ms!

Now, from just about anywhere in your program, when you want to update the servo position, you just have to change the value of the appropriate servo[] index.  Here’s an example main loop:

int main(void) {
    init_clock();
    init_io();
    init_timers();

    int i;
    for (i=0 ; i<20 ; i+=10)
    {
        servo[1] = i;
        servo[2] = i;
        _delay_ms(1000);
    }
}

I should mention that you need to include “pmic_driver.h” from the PMIC app note AVR1305, and “TC_driver.h” from AVR1306.  Also copy in the matching .c files into the same folder.

That’s really about it.  And it’s easy to add on to this and control another servo:

  1. Add an extra index into the “servos[]” array.
  2. Pick an unused timer and add it to the “timer_init()” function.
  3. Cut, paste, and modify timer code for the new timer in the 20ms timer ISR.
  4. Add an ISR for the new timer, again cutting, pasting, and modifying for the new servo.

That about does it.  It seems to work pretty well for my uses.  Make sure and calibrate the limits on your servo variables so that you maximize your reach (for the servos I tested it with, it was between 0 and 270) .  One problem I had was erratic behavior when it collided with another timer occasionally – this was fixed by adding lifting this up from the “LO” level interrupts to the “MED” level interrupts.  It could also be moved even higher to avoid problems even further.  This is an issue with the XMega, where it wouldn’t necessarily have been with an ATMega, because XMega interrupts have changed and a higher level interrupt can interrupt a lower level interrupt.  Good to keep in the back of your mind as you code…

As always, let me know in the comments if you need any help setting this up.

Categories: How-To Tags: , , , ,