October 22, 2024
Chicago 12, Melborne City, USA
C#

Can't correctly print to serial UART using AVR-c on ATMEGA328P Arduino Uno


I’m trying to program an ATMEGA328P Arduino Uno "bare metal" to print to serial over the USB connection to my computer, however I only see replacement characters (�) being printed, both when using screen /dev/ttyACM0 9600 and when using the Arduino IDE serial monitor. I’ve tried different baud rates to no avail, although the baud rate should be 9600. The TX LED flashes regularly, and the � are appearing at the same rate as expected.

I was following the serial print part of the guide: https://archive.md/wqcw6. Using the make instructions from the same guide resulted in no transmission at all, so I used a different make (shown below) which resulted in transmission but just the � being received. I suspect there’s a baud rate issue being caused somewhere.

Here is my code:

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

#ifndef F_CPU
#define F_CPU 16000000UL
#endif

#include <util/delay.h>

#define BAUD 9600

#include <util/setbaud.h>

int uart_putchar(char, FILE*);
void uart_init();

FILE output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);

void uart_init(void) {
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;
    UCSR0C = (1<<UCSZ01) | (1<<UCSZ00); // 8-bit data
    UCSR0B = (1<<TXEN0); // enable TX
}

int uart_putchar(char c, FILE *stream) {
    if (c == '\n') {
        uart_putchar('\r', stream);
    }
    loop_until_bit_is_set(UCSR0A, UDRE0);
    UDR0 = c;
    return 0;
}

int main(void) {
    uart_init();
    stdout = &output;

    while(1) {
        printf("Hello World!\n");
        _delay_ms(500);
    }
    return 0;
}

Here’s my Makefile:

default:
    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o serial-print.o serial-print.c 
    avr-gcc -o serial-print.bin serial-print.o
    avr-objcopy -O ihex -R .eeprom serial-print.bin serial-print.hex
    sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:serial-print.hex

Any tips would be greatly appreciated. Thank you.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video