Thursday, March 11, 2010

ATTINY2313 Serial - March Madness Entry 11

At the micro controller study group, I decided to dedicate myself to getting a serial library that works on the AVR ATtiny2313 micro controller. I've used the serial ports on ATtiny25/45/85's, Atmega48/88/168/328s, and Atmega644s, etc... But the ATtiny2313 has a weird set of registers for serial port. Since I planned on using it later with a serial application, I realized that I would have to heavily adjust some of my code due to the 2313's odd choice in register names.

This code should work. Please note that the receive interrupt echoes the input - probably a good idea to change that if you're using it for an application.

/*
 * serial.c
 *
 *  Created on: Mar 11, 2010
 *      Author: kchester
 */

/** \brief Controls serial communication
 *
 * \file serial.c
 *
 * Initializes and controls serial communication
 *
 * \author keithc@wpi.edu
 * \version 1
 */
#define BAUDRATE 19200
#define BAUD_CALC ((F_CPU/BAUDRATE/16)-1)


#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "FunctionHeader.h"


/** \fn void InitializeSerial()
 * \brief Initializes the USART0.
 * \param void
 * \return void
 */
void InitializeSerial(void)
{
                UBRRH = (unsigned char)(BAUD_CALC>>8);//Set baud rate
                UBRRL = (unsigned char)BAUD_CALC;//Set baud rate
                UCSRB = _BV(TXEN) | _BV(RXEN) | _BV(RXCIE);
                UCSRC = (1<<USBS)|(3<<UCSZ0);//Set frame format
}


/** \fn void serialTx( unsigned char output )
 * \brief Transmits an individual byte over serial.
 * \param unsigned char output
 * \return void
 */
void serialTx( unsigned char output )
{
                while ( !( UCSRA & (1<<UDRE)) ){//Wait to see if buffer is empty
                }
                UDR = output;//Sends data through buffer
}

/** \fn unsigned char serialRx()
 * \brief Receives an individual byte for serial and echoes it back.
 * \param void
 * \return unsigned char received
 */
unsigned char serialRx( void )
{
                char received = UDR;
                serialTx(received);//echos data recived
                return received;//Get and return received data
}

/** \fn void serialTxString( char * str)
 * \brief Transmits a string, byte by byte, until it sees a null terminator.
 * \param char * str
 * \return void
 */
void serialTxString(char * str) {
                int i=0;
                while(str[i] != '\0') {
                    serialTx(str[i++]);
                }
                PORTB ^= 0xFF;
                _delay_ms(1000);
}


/** \fn ISR(USART0_RX_vect)
 * \brief Handles serial receive interrupts.
 * \param void
 * \return void
 */
ISR(USART_RX_vect){
    serialTx(UDR); //Add to buffer
}

1 comment:

  1. Thanks for sharing. Where is "FunctionHeader.h"? Is it really needed?

    ReplyDelete