Make your own dual programmer in AVRDUDE

Modified 9/16/2014

Those of you who have programmed an Arduino through the Arduino or AVR Studio IDE may have noticed the utility that is really doing the work: AVRDUDE (AVR Downloader/UploaDEr).  This is a powerful program that can facilitate programming new sketches on top of a bootloader, load a brand new bootloader or chip image, capture the current firmware programmed on the chip, and set fuse bits (which can render your chip unusable without special tools if you're not careful).


You mean I could have been doing this the whole time?


The LEDgoes USB Communicator supports both programming over serial (bootloader must be present) or via ICSP bitbang (very slow).  The ICSP operation is identical to Adafruit's FTDI Friend product.  The serial programming is identical to the Arduino, except that in my case, I'd like to be able to program two ATmega chips at the same time without switching cables.  What's the best way to do this?

My original train of thought (from Mixing Logic With ISP Circuitry For Programming Firmware) involved using a switch and AND gates to decide which chip would actually get the bits.  Granted, that article was really geared for SPI programming, but the concept is even more applicable to serial programming since our UART lines (TX & RX) are common among both chips on the board.  Trying to program one chip without holding the other in RESET will cause a failure to write the program, as they will both try to send serial output on the same wire & confuse each other.  However, the logic gates used for switching still required either manual intervention or use of a Raspberry Pi which didn't really work out for me at the time.  I thought it was going to come to me needing to get yet another microcontroller just to handle one single bit of output from AVRDUDE to control the RESET lines, which seemed really stupid.  It was getting very annoying to wire up the boards two different ways to program both of the chips, though, so I still drove to find a solution.

After examining a serial port's configuration, and seeing which pins were still available after Arduino's serial programming application had been implemented, I decided it'd be simpler to use AVRDUDE to hold one chip in RESET while the other is programmed.


What if I don't have LEDgoes?


Good news!  You can use an Arduino to do this as well
.  If you haven't familiarized yourself with the ICSP header pins on the Arduino board, you'll get a crash course here.  The "RESET" header pin you can tap into is, obviously, electrically connected to the ATmega RESET pin, but it's also connected to the "RST" pin (#5) on the ICSP header.  AVRDUDE maps this RST signal to the "DTR" (Data Terminal Ready) serial signal coming from the FTDI USB/serial chip.  This is part of the mechanism used under the hood each time you upload a sketch.  However, this new AVRDUDE programmer defined below will also activate the MOSI pin on the ICSP header (#4), which is linked to the RTS signal from the FTDI chip (Request to Send).  Between these two pins (RST <- DTR, and MOSI <- RTS), we can hold one chip in reset while the other one is being programmed.

One small catch: you need to take off the on-board ATmega chip if you don't plan to use it.  For folks with SMD edition Arduinos, you cannot program two external chips without making some adjustments.  The code below assumes you have exclusive use of the RST line (i.e. the "RST" ICSP header used in the diagram below, or the Arduino "RESET" pin).  However, the SMD chip's reset pin is hooked up to this same RST line.  Thus, if you connect an external chip to this RST line while the on-board chip is still in place, the two chips will be programmed at the same time, and that always causes problems.  Usually when this happens, the chips start talking over each other loudly enough to make AVRDUDE fail.  In this case, AVRDUDE passes but the program on the external chip will be all screwed up.

To circumvent this, if you have an SMD-edition Arduino, you'll need to find (or perhaps write) yet another function in AVRDUDE to control a pin *besides* DTR and RTS.  You could pick the TXD pin (which leads to pin 3 / SCK on the ICSP header) or CTS (which goes to ICSP pin 1 / MISO).  Of course, there's no need to take these precautions if you're looking to program the SMD chip and one external chip; just make sure the external chip's reset is only hooked up to RTS (ICSP pin 4 / MOSI).

It's good to keep that in mind anyway, since with those extra functions to utilize TXD & CTS, you could program up to four ATmegas (or 16 if you wanted to get fancy with combinational logic).

Here's what the breadboard setup looks like (for the non-SMD-edition crowd):


Depending on what jumper cables you have around, you can route the pink cable into the RESET pin on the regular Arduino headers instead of the RST pin on the ICSP headers.  It doesn't matter which chip is hooked into RST or MOSI as long as you properly track which one gets programmed when.


Building Your Own AVRDUDE In Linux

To get started with this, I had to download the code and load a bunch of dependencies for it to compile.  After having looked at MinGW for Windows, I thought it'd be a little bit less effort to get it going in Linux.  So here's roughly how it went:


  • Checked out the SVN repository from http://savannah.nognu.org/svn/?group=avrdude
  • Learned about autoconf, a cross-platform build tool (and what AVRDUDE uses to get built)
  • Ran autoconf configure.ac
  • Fought with a "error: possibly undefined macro: AM_INIT_AUTOMAKE" (for which this post suggested the correct solution for fixing this issue):
    • Add AC_CONFIG_MACRO_DIR([m4]) to configure.ac -- it was already present in my case
    • libtoolize --force
    • aclocal
    • autoheader
    • automake --force-missing --add-missing
    • autoconf
  • Installed missing dependencies, such as developer libraries for libusb & libftdi (the AVRDUDE configure script will tell you what you're missing), plus flex (but not its friend bison), and yacc
  • Ran autoconf configure.ac again after these missing dependencies were satisfied
  • sudo ./configure; sudo make; sudo make install
Thus was born my very own AVRDUDE!


Cloning the Arduino Programmer into "BritebloxUSB"


Since my programmer is basically an "arduino" programmer (but I wanted to program two devices at once instead of just one), I decided to base my code heavily around theirs.  After poking around to study how it was implemented and tied in with the whole application, I was able to produce the desired behavior using the following files:

  • arduino.c (saved as briteblox.c)
  • arduino.h (saved as briteblox.h)
  • pgm_type.c
  • Makefile.am

Later on, you will see what I did to these files to get the programmer working as desired.  I also should have modified the following files (but took the lazy man's way out since I was only looking for Linux support at the time):

  • ser_posix.c
  • ser_win32.c

I'll explain why I need to modify these files later.  After each time I'd change any of these files, I would run:

autoconf; sudo make; sudo make install; sudo cp /usr/local/etc/avrdude.conf.stevo /usr/local/etc/avrdude.conf

This rebuilds the AVRDUDE binary and also reinstates the changes I need into the configuration file so it recognizes "britebloxusb" as a programmer.

AVRDUDE allows programmers to send the signals used for programming to different output pins than expected.  For example, the pulse sent to reset the AVR chips goes through the DTR and RTS pins from the FTDI chip.  By splitting up the function of the DTR & RTS pins to behave separately, I can "lightly tap" one chip into RESET (so it will be programmed) and hold the other chip in RESET (so it will "sleep through" all the instructions being sent to program its neighbor).  This was achieved by modifying the _open() function, and adding a new function called briteblox_set_dtr_rts().  (This new function needs to be modified to fit nicely into ser_posix.c and ser_win32.c.)

The programmer accepts an optional argument (through the _parseextparms() function) that allows you to specify which signal gets held down the entire time.  Without specifying "-x reverse", DTR is held low the entire time.  When this parameter is included, though, RTS is held low the entire time.  This way, to program both AVRs without rearranging the cables, all you need to enter on the command line is:

avrdude -p atmega168 -c britebloxusb -P /dev/ttyUSB0 -D -U <what to do>; avrdude -p atmega168 -c britebloxusb -P /dev/ttyUSB0 -D -U <what to do> -x reverse

And if you ever write anything invalid for -x, the britebloxusb programmer will politely remind you what options are supported by -x.  Right now, it's just help and reverse.


Code


While this isn't quite perfect nor polished yet (the output from _close() and _teardown() still needs to be reconciled a bit too), here it is for your enjoyment and edification.  Soon I hope to commit this (cleaned up) into the mainline AVRDUDE source code for enjoyment by all.

britebloxusb.c: 


/*
 * avrdude - A Downloader/Uploader for AVR device programmers
 * Copyright (C) 2009 Lars Immisch
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* $Id: $ */

/*
 * avrdude interface for britebloxusb programmer
 *
 * The britebloxusb programmer is mostly a STK500v1, just the signature bytes
 * are read differently.
 */

#include "ac_cfg.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>

#include "avrdude.h"
#include "libavrdude.h"
#include "stk500_private.h"
#include "stk500.h"
#include "britebloxusb.h"

/* flags */
#define BBX_FLAG_REVERSE          (1<<0)

/* set dtr & rts separately; the usual "serial" function lib makes you do them together */
/* FIXME: This will only work in POSIX-land!!! */
static int briteblox_set_dtr_rts(union filedescriptor *fdp, int dtr_on, int rts_on)
{
  unsigned int ctl;
  int           r;

  r = ioctl(fdp->ifd, TIOCMGET, &ctl);
  if (r < 0) {
    perror("ioctl(\"TIOCMGET\")");
    return -1;
  }

  if (dtr_on) {
    /* Set DTR */
    ctl |= TIOCM_DTR;
  }
  else {
    /* Clear DTR */
    ctl &= ~TIOCM_DTR;
  }

  if (rts_on) {
    /* Set RTS */
    ctl |= TIOCM_RTS;
  }
  else {
    /* Clear RTS */
    ctl &= ~TIOCM_RTS;
  }

  r = ioctl(fdp->ifd, TIOCMSET, &ctl);
  if (r < 0) {
    perror("ioctl(\"TIOCMSET\")");
    return -1;
  }

  return 0;
}

/* read additional params */
static int britebloxusb_parseextparms(struct programmer_t *pgm, LISTID extparms)
{
  LNODEID ln;
  const char *extended_param;
  char reset[10];
  char *preset = reset;   /* for strtok() */
  int spifreq;
  int cpufreq;
  int serial_recv_timeout;

  for (ln = lfirst(extparms); ln; ln = lnext(ln)) {
    extended_param = ldata(ln);
    if (strcmp(extended_param, "reverse") == 0) {
      pgm->flag |= BBX_FLAG_REVERSE;
      avrdude_message(MSG_INFO, "%s: Reversing reset signals for this run...\n", progname);
      continue;
    } else if (strcmp(extended_param, "help") == 0) {
      avrdude_message(MSG_INFO, "%s: britebloxusb: Available Extended Commands:\n"
                      "\thelp\tPrints this help message\n"
                      "\treverse\tHolds down RTS instead of DTR throughout programming\n", progname);
      return -1;
    } else {
      avrdude_message(MSG_INFO, "%s: extended parameter %s is not understood.  Use \"-x help\" for all options.\n", progname, extended_param);
      return -1;
    }
  }
}

/* read signature bytes - britebloxusb version */
static int britebloxusb_read_sig_bytes(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m)
{
  unsigned char buf[32];

  /* Signature byte reads are always 3 bytes. */

  if (m->size < 3) {
    avrdude_message(MSG_INFO, "%s: memsize too small for sig byte read", progname);
    return -1;
  }

  buf[0] = Cmnd_STK_READ_SIGN;
  buf[1] = Sync_CRC_EOP;

  serial_send(&pgm->fd, buf, 2);

  if (serial_recv(&pgm->fd, buf, 5) < 0)
    return -1;
  if (buf[0] == Resp_STK_NOSYNC) {
    avrdude_message(MSG_INFO, "%s: stk500_cmd(): programmer is out of sync\n",
progname);
return -1;
  } else if (buf[0] != Resp_STK_INSYNC) {
    avrdude_message(MSG_INFO, "\n%s: britebloxusb_read_sig_bytes(): (a) protocol error, "
                    "expect=0x%02x, resp=0x%02x\n",
                    progname, Resp_STK_INSYNC, buf[0]);
return -2;
  }
  if (buf[4] != Resp_STK_OK) {
    avrdude_message(MSG_INFO, "\n%s: britebloxusb_read_sig_bytes(): (a) protocol error, "
                    "expect=0x%02x, resp=0x%02x\n",
                    progname, Resp_STK_OK, buf[4]);
    return -3;
  }

  m->buf[0] = buf[1];
  m->buf[1] = buf[2];
  m->buf[2] = buf[3];

  return 3;
}

static int britebloxusb_open(PROGRAMMER * pgm, char * port)
{
  union pinfo pinfo;
  strcpy(pgm->port, port);
  pinfo.baud = pgm->baudrate? pgm->baudrate: 19200;
  if (serial_open(port, pinfo, &pgm->fd)==-1) {
    return -1;
  }

  /* Set DTR & RTS to reset both chips */
  briteblox_set_dtr_rts(&pgm->fd, 1, 1);
  usleep(250*1000);
  if ((pgm->flag & BBX_FLAG_REVERSE) == 0) {
    /* (Normal) Clear only RTS in order to resume communication with the desired chip */
    briteblox_set_dtr_rts(&pgm->fd, 1, 0);
  } else {
    /* (Reversed) Clear only DTR in order to resume communication with the desired chip */
    briteblox_set_dtr_rts(&pgm->fd, 0, 1);
  }
  usleep(50*1000);

  /*
   * drain any extraneous input
   */
  stk500_drain(pgm, 0);

  if (stk500_getsync(pgm) < 0)
    return -1;

  return 0;
}

static void britebloxusb_close(PROGRAMMER * pgm)
{
  /* Release the other chip from reset */
  briteblox_set_dtr_rts(&pgm->fd, 0, 0);
  serial_close(&pgm->fd);
  pgm->fd.ifd = -1;
}

static void britebloxusb_teardown(PROGRAMMER * pgm)
{
  britebloxusb_close(pgm);
}

const char britebloxusb_desc[] = "britebloxusb dual AVR programmer";

void britebloxusb_initpgm(PROGRAMMER * pgm)
{
  /* This is mostly a STK500; just the signature is read
     differently than on real STK500v1 
     and the DTR signal is set when opening the serial port
     for the Auto-Reset feature */
  stk500_initpgm(pgm);

  strcpy(pgm->type, "britebloxusb");
  pgm->read_sig_bytes = britebloxusb_read_sig_bytes;
  pgm->open = britebloxusb_open;
  pgm->close = britebloxusb_close;

  /* Optional functions */
  pgm->parseextparams = britebloxusb_parseextparms;
  pgm->teardown = britebloxusb_teardown;

}


britebloxusb.h:


/*
 * avrdude - A Downloader/Uploader for AVR device programmers
 * Copyright (C) 2009 Lars Immisch
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* $Id: $ */

#ifndef britebloxusb_h__
#define britebloxusb_h__

extern const char britebloxusb_desc[];
void britebloxusb_initpgm (PROGRAMMER * pgm);

#endif


Additions to Makefile.am:


libavrdude_a_SOURCES = \
...
avrftdi_tpi.c \
avrftdi_tpi.h \
avrpart.c \
bitbang.c \
bitbang.h \
britebloxusb.c \
britebloxusb.h \
buspirate.c \
buspirate.h \
butterfly.c \
butterfly.h \
config.c \

confwin.c \
...


Additions to pgmtype.c:


#include "avrftdi.h"
#include "britebloxusb.h"
#include "butterfly.h"
...
const PROGRAMMER_TYPE programmers_types[] = {
        {"arduino", arduino_initpgm, arduino_desc},
        {"avr910", avr910_initpgm, avr910_desc},
        {"avrftdi", avrftdi_initpgm, avrftdi_desc},
        {"britebloxusb", britebloxusb_initpgm, britebloxusb_desc},
        {"buspirate", buspirate_initpgm, buspirate_desc},
...


Additions to avrdude.conf.stevo:


programmer
  id    = "arduino";
  desc  = "Arduino";
  type  = "arduino";
  connection_type = serial;
;

programmer
  id    = "britebloxusb";
  desc  = "BriteBlox USB Dual Serial Programmer";
  type  = "britebloxusb";
  connection_type = serial;
;
# this will interface with the chips on these programmers:
#

# http://real.kiev.ua/old/avreal/en/adapters

Comments

Popular posts from this blog

Less Coding, More Prompt Engineering!

Start Azure Pipeline from another pipeline with ADO CLI & PowerShell

An Augmented Reality Experience to Complement a Vintage Pinball Machine