Friday 29 July 2011

Using an Arduino as an USB UART

As you know I'm working on some modest electronic projects involving microcontrollers. And when you debug these little beasts, having a text output is no luxury. The best way to do this is by using a USB UART adapter. But when you don't have one, maybe you are still lucky and have an Arduino Duemilanove lying around. This Arduino uses an FTDI chip as a USB USART interface for the AVR chip. You can check the datasheet of the FTDI chip here (pdf), and the schematics of the Arduino here (pdf).

Sweet, all the parts are here, now let's put all this together.

First you need to program your Arduino to set the RX and TX pins to Input. This will set the logic gates of the pins to a open state that won't conflict with the signals comming from our own chip. To do this just create a new sketch in the Arduino development environment and copy this code:

void setup()
{
    // put RX and TX of the AVR to a rest
  pinMode(0, INPUT);
  pinMode(1, INPUT);
}
void loop() {
}

Upload this to the Arduino and run the Serial Monitor. Note you have to leave the RT/TX unplugged when programming the Arduino. You can now set the data transfer rate to an appropriate value. For my case I will use 115200 bauds.

Now we can hook our own microcontroller to the FTDI chip. Link the TX of your chip to the TX of the board (it actually corresponds to the RX of the FTDI chip). That's pretty much the only hardware manipulation necessary.

Last step you need to setup the USART of you microchip. Here is an example of how I set it for my project using a PIC18f. This example uses the sdcc iolib:
  usart_open(
             USART_TX_INT_OFF &
             USART_RX_INT_OFF &
             USART_BRGH_HIGH &
             USART_EIGHT_BIT &
             USART_ASYNCH_MODE,
             103);
  BAUDCONbits.BRG16 = 1;
  stdout = STREAM_USART;
  printf("Starting USB\n");

You will need to calculate the proper Baud Generator value for your project. Refer to the datasheet of your microcontroller for this. Here 103 corresponds to the following calculation taken from the PIC18F2450 data sheet (using 48Mhz clock, wants 115200 bauds, 4 is because using Aynch transfer with BRG16 and BRGH): ((48000000 / 115200) / 4) - 1.

Just compile that, upload to the boad and the debug message magicly apears on the Arduino console:
Starting USB

No comments:

Post a Comment