Wednesday, February 1, 2012

Using stdio.h's "printf" Function on an Atmel AVR Microcontroller

#include <avr/io.h>
#include <stdio.h>

#define BAUDRATE 57600

static void put_char(uint8_t c, FILE* stream);
static FILE mystdout = FDEV_SETUP_STREAM(put_char, NULL, _FDEV_SETUP_WRITE);

int main(void)
{

    UBRR0H = ((F_CPU / 16 + BAUDRATE / 2) / BAUDRATE - 1) >> 8;
    UBRR0L = ((F_CPU / 16 + BAUDRATE / 2) / BAUDRATE - 1);
    UCSR0B |= (1 << TXEN0);

    stdout = &mystdout;

    for(int i = 0; i >= 10; i++)
        printf("testing %d\n\r", i);
}

static void put_char(uint8_t c, FILE* stream)
{
    if (c == '\n') 
     put_char('\r', stream);
  
   while(!(UCSR0A & (1 << UDRE0)));
    UDR1 = c;
}

No comments:

Post a Comment