Wednesday 7 February 2018

Interfacing HC-05 with Atmega8

In this post, we will interface bluetooth module (HC-05) with atmega8. Atmega8 is a 28-pin IC and it has three ports viz., PORTB, PORTC and PORTD and it has total 23 gpio pins. It has internal rc oscillator, that is user selectable from  1, 2, 4 or 8 MHz.

We are using 8 Mhz internal rc oscillator.

Compiler Used: GCC

Connection is as follows:

Atmega8                                     BT module
RX            ============>     TX
TX            ============>     RX
GND         ============>     GND
VCC         ============>     VCC

We are using uart at baud rate 9600. Make sure that BT module and atmega8 both have same baud rate.


Source Code:

#define F_CPU 8000000UL
#define BAUD 9600
#define MYUBRR F_CPU/16/BAUD-1

#include<avr/io.h>
#include<util/delay.h>

void USART_Transmit(unsigned char);
void USART_Init( unsigned int);
unsigned char USART_Receive( void );


void main( void )
{
unsigned char a=0;
DDRC=0xff;  
USART_Init(MYUBRR);
//USART_Transmit('d');
while(1)
{
a=USART_Receive();

switch(a)
{
case '1':
PORTC=0x01;
break;
case '2':
PORTC=0x02;
break;
case '3':
PORTC=0x04;
break;
case '4':
PORTC=0x00;
break;
}
_delay_ms(100);
}

}

void USART_Init( unsigned int ubrr)
{
/* Set baud rate */
UBRRH = (unsigned char)(ubrr>>8);
UBRRL = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSRB = (1<<RXEN)|(1<<TXEN);
/* Set frame format: 8data, 2stop bit */
UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0); 
}

unsigned char USART_Receive( void )
{
/* Wait for data to be received */
while ( !(UCSRA & (1<<RXC)) )
;
/* Get and return received data from buffer */
return UDR;
}

/*   End of code */


No comments:

Post a Comment