I have worked with ATMEGA328P using Arduino libraries, but new to actual register level coding. To start with that, I have written code for basic Serial.print in AVR STUDIO IDE. I tried to check it's output on Serial monitor of Arduino IDE. I could not see any result, as transmitter LED of Arduino UNo board is not blinking, I conclude that I have done something wrong, but unable to debug it. I would appreciate if one can suggest books to learn Register level coding for Atmega328P.

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

void beginSerial(int baud){
    uint16_t UBRR_value=lrint((F_CPU/(16 *baud))-1);
    UCSR0A = 1<<U2X0;
    UBRR0H=(unsigned char) (UBRR_value >>8);
    UBRR0L=(unsigned char) UBRR_value;
    UCSR0B=(1<<RXEN0) | (1 <<TXEN0);
    UCSR0C=(1<<USBS0) | (3 <<UCSZ00);

int main(void)
    DDRB |=(1<<PINB5);
    PORTB &=(1<<PINB5);
    while (1) 
        while(! (UCSR0A & (1 << UDRE0)));
        UDR0 ='A';
  • 1
    \$\begingroup\$ I think you're missing a semicolon at the end of your while loop in main. Currently it'll only write to the register when UDRE0 is not set. \$\endgroup\$ – Harry Beadle Aug 22 '19 at 10:46
  • \$\begingroup\$ Baud rate calculation is also wrong as with U2X feature one bit is 8 clocks. \$\endgroup\$ – Justme Aug 22 '19 at 11:05
  • \$\begingroup\$ Please enter your code not as an image. \$\endgroup\$ – Mike Aug 22 '19 at 11:17
  • \$\begingroup\$ Corrected major mistake ';', still not able to see the correct character on the serial monitor, @Justme would u explain the mistake in U2X assignment \$\endgroup\$ – dss2309 Aug 22 '19 at 11:27
  • \$\begingroup\$ You can configure the UART for 8 or 16 times oversampling. You configured it for 8x but are calculating for 16. Either do not set U2X0, or change the clock division calculation to use 8. \$\endgroup\$ – Chris Stratton Aug 22 '19 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.