Search code examples
carduinouartatmega

How do i fetch data from UDRn on Mega2560?


Noob question: I'm trying to learn about UART on an ARDUINO. I wrote some very simple code and for some reason, i can't make the receive() function work. I don't think it fetches the data from the UDR register. I'm using a small OLED display and i want to print the received data to it. No data is being printed to the display, when i run the code. I connected the ports TX1 and RX1 with a wire on the board. I tried finding youtube videos and have been reading alot. Appearently not enough. Any ARDUINO expert who knows what to do?

#include <avr/io.h>
#include "ssd1306.h"
#include "I2C.h"
#include <stdio.h>
#include <util/delay.h>

void initOLED();
void initUART1();
void receive();
void transmit();

int main(void)
{

    I2C_Init();
    initOLED();                     //initialiaze OLED
    while (1) 
    {
        transmit();
        receive();
    }
}

void initOLED()
{


    I2C_Init();
    InitializeDisplay();
    clear_display();

}

void initUART1(void)
{
    DDRD = 0x08;                     //TXD1 set to output
    UBRR1L = 51;                     //Baudrate 19200
    UBRR1H = 0;                     //upper four bits of baudrate
    UCSR1A = 0x02;                  //Double speed mode
    UCSR1B = 0x18;                  //Enable receive and transmit
    UCSR1C = 0x06;                  //1 stop bit, 8-bit, no parity
}

void transmit()
{
    char b = 'a';
    while(!(UCSR1A & (1<<UDRE1))); //wait for an empty UDR register
    UDR1 = b;                      //load character in register
}
void receive()
{
    int Y = 0;                    //Y coordinate for cursor on the display
    char d;
    while(!(UCSR1A & (1<<RXC1))); //wait for unread data in the receive buffer
    d = UDR1;                     //set UDR register in character d

    sendCharXY(d, 1, Y);          //send character to display
}

Solution

  • It looks like you never call initUART1().