Reputation: 101
I am trying to deal with the concept of serial communication with the ATmega328P. I'm quite new to this, but this is the code I've currently written. Basically we have enter in a character from serial communication into the RX of the ATmega chip and want the TX to transmit back same character that was sent from the serial terminal. I believe this code does receive the transmission, but I cannot figure out why it does not transmit the entered character.
int main(void)
{
/* For the microcontroller: set the baud rate to 19200 */
UBRR0 = 25;
/*
** Enable transmission and receiving via UART and also
** enable the Receive Complete Interrupt.
*/
// UCSR0A = (1<<RXC0)|(1<<UDRE0);
UCSR0B = (1<<RXCIE0)|(1<<UDRIE0)|(1<<RXEN0)|(1<<TXEN0);
// Receiving data
// wait for data
while(!(UCSR0A & (1 << RXC0)));
// return data
return UDR0;
//Transmitting data
/* No need to set UCSR0C - we just want the default value */
/* Enable interrupts */
sei();
/* Sit back and let it happen - this will loop forever */
for (;;) {
}
}
/*
* Define the interrupt handler for UART Receive Complete - i.e. a new
* character has arrived in the UART Data Register (UDR).
*/
/*UART Register*/
ISR(USART0_UDRE_vect)
{
/* A character has been received - we will read it. If it is
** lower case, we will convert it to upper case and send it
** back, otherwise we just send it back as is
*/
char input;
/* Extract character from UART Data register and place in input
** variable
*/
UDR0 = input;
}
ISR(USART0_RX_vect) {
char input = UDR0;
printf_P(PSTR("%c"), input);
}
Upvotes: 0
Views: 1577
Reputation: 4654
There is no sense in your code.
1)
int main(void)
{
...
return UDR0;
This has no sense: You're returning from main
to ... where? Actually, when you exit main routine, the program is halted by entering the dead loop.
2)
ISR(USART0_UDRE_vect)
{
...
char input;
...
UDR0 = input;
}
you're transmitting content of the variable input
. Which is declared above remains undefined. You never assign anything to the variable. I bet the compiler gave you a lot of warnings.
3)
ISR(USART0_RX_vect) {
char input = UDR0;
printf_P(PSTR("%c"), input);
}
what do you expect from 'printf'. Where it should to print the result, when running on a MCU?
In fact the code may be much simpler
int main(void)
{
// Sets 19200 only when MCU is running at 8MHz
UBRR0 = 25;
// enable receiver and transmitter
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
for(;;) { // infinite loop
// Receiving data
// wait for data
while(!(UCSR0A & (1 << RXC0)));
// read the data byte from the the receiver buffer
unsigned char data = UDR0;
// Wait for the transmitting buffer to be empty
while(!(UCSR0A & (1 << UDRE0)));
// Send the data
UDR0 = data;
}
}
Upvotes: 1