UART on Arduino mega with registers printing boxes and question marks

I tried to implement UART by using registers on Arduino mega. But i'm not getting any significant output. The same code works on Atmega 128 for some reason.

#define BAUD 9600
#define UBRR_VALUE ((16000000 / (16UL * BAUD)) - 1)
#include <stdio.h>
#include <avr/io.h>

uint16_t x;

void UART_init(){

  UCSR0C|=(1<<UCSZ00)|(1<<UCSZ01); //8 bit data
  UBRR0H = (uint8_t)(UBRR_VALUE >> 8);
  UBRR0L|=(uint8_t)(UBRR_VALUE); //9600 Baud rate
  UCSR0B|=(1<<TXEN0)|(1<<RXEN0);  //UART1 Tx Rx enable
}




void UART_send(char y){
  
  while(!(UCSR0A && (1<<UDRE0))); //Check if Tx buffer is empty.
  UDR0=y;
}


int main(){
  UART_init();
  while(1){
    UART_send('p');
    _delay_ms(100);
  }
}

This prints question marks, and any integer type that I send prints boxes. I have verified the baud rate to be correct. what might be the error?

It's possible that the MEGA bootloader leaves USART0 partially configured.
Be sure to initialize ALL of the control registers; especially U2X0 in UCSR0A
(that also means you should use UCSRC = xxx and UCSR0B = yyy instead of the |= form (and UBRR0L too!))

I did so. The only result is that it is now able to print characters on the serial terminal.
My intention is to send hexadecimals. Is that possible ? I really can't see any error to be frank.

Is this a big difference?

Hexadecimal is not a new type of data, it is just a representation of the bytes, as well a chars.

try this:

int main(){
  UART_init();
  while(1){
    UART_send(0x30);    // you should receive '0' in Monitor
    _delay_ms(100);
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.