Arduino Mega (ATMega2560) UART does not send [closed]

I set up Atmel Studio on a Windows PC using this tutorial. Afterwards I proceeded to implement a UART. But it didn't work (no signal measurable with oscilloscope). So I just copied a simple UART example from the ATMega2560 datasheet Section 22.5 and 22.6.

#define FOSC 16000000
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
#define F_CPU 16000000
#include <avr/io.h>
#include <util/delay.h>

void USART_Init(unsigned int ubrr);
void USART_Transmit(unsigned char data);

int main(void)
{
USART_Init(MYUBRR);

while(1)
{
USART_Transmit('A');
}
}

void USART_Init(unsigned int ubrr)
{
UBRR0H = (unsigned char) (ubrr>>8);
UBRR0L = (unsigned char) ubrr;

UCSR0B = (1<<RXEN0)|(1<<TXEN0);

UCSR0C = (1<<USBS0) | (3<<UCSZ00);
}

void USART_Transmit(unsigned char data)
{
while(!(UCSR0A & (1<<UDRE0)))

UDR0 = data;

}


But even this example does not work. I took an oscilloscope and connected it to the TX0 pin and a ground pin, but no signal was received. When I removed the USART_Init function, the character A was sent over UART but of course with a wrong baud rate. Did I forget about something?

Does anyone have an idea/hint? Is something wrong with my question?

closed as off-topic by Chris Stratton, RoyC, Oleg Mazurov, Huisman, evildemonicAug 19 at 15:59

• This question does not appear to be about electronics design within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

• I'm voting to close this question as off-topic because it has been abandoned for a month by an asker who has not returned to the site since the day after asking, making it impossible to know if the proposed solution has solved their problem. – Chris Stratton Aug 15 at 11:40

I think the problem may be that your while loop within the USART_Transmit() function just needs some braces:

void USART_Transmit( unsigned char data )
{
while (!(UCSR0A & (1 << UDRE0))) {}
UDR0 = data;
}


I was able to get this working with Atmel Studio 7 and an Arduino Mega 2560.

Just replace:

UBRR0H = (unsigned char) (ubrr>>8);
UBRR0L = (unsigned char) ubrr;


with this:

UBRR0H = 0 ;
UBRR0L = 103 ; // for 9600 Baudrate at F_osc = 16 MHz and for 1200
BaudRate at F_osc = 1 MHz


Refer to the following Image:

• "Do this not that" answers are not very useful - you've not explained any theory of what you believe to be wrong. One might try your idea to see if it makes any difference, but it should not as you are proposing the same values the question code should produce, but without the flexibility of the asker's original. – Chris Stratton Aug 15 at 11:37