I have connected my AVR USART to file stream so as to make it easy to send formatted strings on ATmega8
From the AVR, I can send(TX) just fine. However, I am not receiving anything. Can't put my hand on it but it looks like I'm overlooking something very basic.
uart.c
#define FOSC 8000000
#define BAUD_RATE 38400
#define UBRR_VALUE (uint16_t)(FOSC/16/BAUD_RATE-1)
#include "uart.h"
FILE uart0_str = FDEV_SETUP_STREAM(UARTSendByte, UARTReceiveByte, _FDEV_SETUP_RW);
void UART_INIT(void)
{
UBRRH = (uint8_t)(UBRR_VALUE>>8); //set UBRR register
UBRRL = (uint8_t)UBRR_VALUE;
UCSRC = (1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0) | (1<<USBS);//set frame format: asynchronous,8data,2 stop,no parity
UCSRB = (1<<TXEN) | (1<<RXEN) ;
_delay_ms(10);
stdin=&uart0_str;
stdout=&uart0_str;
}
void UART_WRITE_STRING(char* str)
{
printf("%s",str);
}
int UARTSendByte(char u8data, FILE *stream)
{
if(u8data=='\n')
{
UARTSendByte('\r',stream);
}
while(!(UCSRA&(1<<UDRE))){};
UDR = u8data;
return 0;
}
int UARTReceiveByte(FILE *stream)
{
printf("hello1\r");
UART_WRITE_STRING("hello1\r");
uint8_t data;
// Wait for byte to be received
while(!(UCSRA&(1<<RXC))){};
data=UDR;
//echo input data
UARTSendByte(data,stream);
// Return received data
return data;
}
main.c
#include "uart.h"
#include "twi.h"
#include "ds1307.h"
void bootCode(void);
int main (void)
{
DDRC = 0x01; //set PC0 as output
PORTC = 0x01; //turn on PC0
DDRD = 0x02; //PD0 = RXD = INPUT,PD1 = TXD = OUTPUT
UART_INIT(); //initialize UART
TWI_INIT(); //initialize TWI
UART_WRITE_STRING("ANKIT.*****@GMAIL.COM\r");
UART_WRITE_STRING("JUNE 16, 2014\r");
UART_WRITE_STRING("####################################\r\r\r\r");
while(1)
{
};
}
When I run this, I get the printed strings, but there is no response whatsoever to the text I input.
when I send the text, ideally it should be echoed back on the terminal + I should also get the "hello1" strings hard-coded in the UARTReceiveByte function
UPDATE
While looking at my code I had another thought.
Since I am binding my USART input and output to the standard file streams => if in order to TX from AVR I need to use "printf". By the same logic, the data entered from my PC terminal will not be valid unless there is a "scanf" call in my code.
So as a test, I added a line in my main.c before the infinite loop
unit8_t d;
scanf("%c",&d);
Now when I enter something at the terminal i do get "hello1" 2 times printed on the terminal (as coded in the UARTReceiveByte function).
As a side question, while I am using FILE streams, can I also use USART interrupts?
Best Answer
As suggested in the comments, there was no call to the USARReceiveByte function for the lack of any scanf statement. This solved the issue.