Wednesday, 15 June 2011

Using USART Receiver interrupts in Atmega32


In my previous blog post here, i discussed about the basic usage of USART communication. But to make the program more efficient we make use of interrupts. Using interrupts the micro-controller doesn't need to poll the USART Rx continuously.The incoming data stream causes the micro-controller to be interrupted from its current routine and serve the incoming interrupt by going to its ISR address.

 So in case of the previous blog the micro-controller can perform actions according to the received data from USART. But in cases were we want the micro-controller to perform tasks independent of the USART data then we use interrupts so that the actions of USART Rx data can be performed in the interrupt service routine and the some other task independent of USART can be performed in the infinite while loop.

The same header file usart.h used previously is reproduced. For deatils of its impementation refer to the previous blog here.
#ifndef USART_H_
#define USART_H_
void USARTInit(void);
void USARTInitRecieverInterrupt(void);
int USARTSendByte(char data, FILE *stream);
int USARTReceiveBytewithEcho(FILE *stream);
int USARTReceiveByteWithoutEcho(FILE *stream);
void USARTInit(void)
{
UCSRA=0x00;
UCSRB=0x18;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x67;
}
void USARTInitRecieverInterrupt(void)
{
UCSRA=0x00;
UCSRB=0x98;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x67;
}
int USARTSendByte(char data, FILE *stream)
{
if(data == '\n')
{
USARTSendByte('\r', 0);
}
while(!(UCSRA&(1<<UDRE))){};
UDR = data;
return 0;
}
int USARTReceiveByteWithEcho(FILE *stream)
{
char data;
while(!(UCSRA&(1<<RXC))){};
data=UDR;
USARTSendByte(data,stream);
return data;
}
int USARTReceiveByteWithoutEcho(FILE *stream)
{
uint8_t data;
while(!(UCSRA&(1<<RXC))){};
data=UDR;
return data;
}
#endif
view raw usart.h hosted with ❤ by GitHub

For implementing interrupts we need to import the header file avr/interrupts.h which contains the ISR addresses of respective ave chips.For USART receiver interrupt the isr function is defined as ISR(USART_RXC_vect){}. The logic for the actions against USART Rx interrupt has to be coded in this function.

#include <stdio.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "usart.h"
FILE usart0_str = FDEV_SETUP_STREAM(USARTSendByte, USARTReceiveByteWithEcho, _FDEV_SETUP_RW);
ISR(USART_RXC_vect)
{
char x;
scanf("%c",&x);
printf("\n%c",x);
}
int main()
{
stdin = &usart0_str;
stdout = &usart0_str;
USARTInitRecieverInterrupt();
sei();
while(1){}
return 0;
}

In this example the incoming character is echoed back to the terminal. Nothing great in that but its a start.











No comments:

Post a Comment

Popular Posts