HI,
I have a simple code that receives and transmits string through UART. I use ATMEGA 168.
So according to my code I transmit a string using cool term and the controller receives it.The controller the compares the string .If the strings match then the controller sends back "K" , which will be displayed in the cool term.
If the strings don't match the controller sends back"AT" followed by carriage return and new line.
But when I execute the code and if the strings don't match it returns back "AT";but I do not get a new line.It prints "AT" continuously.
#include <avr/io.h> #include <string.h> #include <util/delay.h> #define F_CPU 8000000UL #define BAUD 9600 #define MYUBBR F_CPU/16/BAUD-1 void uart_init(unsigned int ubrr) { // Setting the baud rate to ubrr UCSR0A = 0<<U2X0; UBRR0H = (unsigned char)(ubrr >> 8); UBRR0L = (unsigned char)ubrr; //Setting the frame format to 8 data bit, no parity bit, 1 stop bit UCSR0C = 3<<UCSZ00; UCSR0B = (1<<TXEN0)|(1<<RXEN0); } void USART_Transmit( unsigned char data ) { while (!(UCSR0A & (1<<UDRE0))); UDR0 = data; } unsigned char USART_Receive() { while (!(UCSR0A & (1<<RXC0))); return UDR0; } void transmit_string(char* data) { int i; for (i=0;data[i] != '\0';i++) { USART_Transmit(data[i]); } } void receive_string(char* dat) { char command[4]; command[0] = '\0'; command[1] = '\0'; command[2] = '\0'; command[3] = '\0'; int index = 0; while ((command[2] != 0x0D) && (command[3] != 0x0A)) { dat= USART_Receive(); index += 1; if (index > 3) { command[0] = dat[index - 4]; command[1] = dat[index - 3]; command[2] = dat[index - 2]; command[3] = dat[index - 1]; } } dat[index-2] = '\0'; } int main(void) { // Setting system clock to 8MHz CLKPR = (1 << CLKPCE); CLKPR = 0; uart_init(MYUBBR); while(1==1) { char dat[10]; receive_string(dat); if(strcmp(dat,"OK")==0) { UDR0='k'; } else { char data[]="AT"; transmit_string(data); UDR0='\r'; UDR0='\n'; _delay_ms(1000); } } }
Kindly point out the mistake .