#define F_CPU 16000000UL						    // тактирование 8Mhz
#include <avr/io.h>      						// Опребеляет имена для портов ввода-вывода
#include <util/delay.h>  					  	// Дает возможность формирования задержки
#include <string.h>

#define led 3
#define RS	2
#define E	1
#define RW	0

#define DATA 1
#define COM  0

void PORTs_Init(void);
void LCD(unsigned char RS_level, unsigned char byte);
void LCD_STRING(unsigned char *message);

int main(void)
{	
	_delay_ms(500);
		
	PORTs_Init();

	LCD(COM, 0x30);  		    
	_delay_ms(4);				
                                
	LCD(COM, 0x30);				
	_delay_us(100);				

	LCD(COM, 0x30);
	_delay_ms(10);
 	
	LCD( COM, 0x3C );  // 0x3C для 8 битной шины, 0x2C для 4 битной шины!!! 
	_delay_ms(10);

	LCD( COM, 0x0C );
	_delay_ms(10);

	LCD( COM, 0x01 );
	_delay_ms(10);
	
	LCD_STRING("Hello hd44780");
	
	LCD( COM, 0xC0 );

	LCD_STRING("I`m happy now!");

	


	while(1)
	{
		PORTD ^= (1<<led);        // мигаю светодиодом что б скучно не было
		_delay_ms(2000);
	}
}

void PORTs_Init(void)
{	
	DDRA  = 0;  		
	PORTB = 0;
	DDRB  = (1<<RS)|(1<<E)|(1<<RW);
	DDRD  = (1<<led);
}

void LCD(unsigned char RS_level, unsigned char byte)
{
	if ( RS_level == COM )
	{
		PORTB &=~ (1<<RS);
	}

	if ( RS_level == DATA )
	{
		PORTB |=  (1<<RS);
	}
	
	DDRA = 0xFF;             // порт на выход для 4 битной шины 0xF0; для высокоимпедансного состояния 0...3 PB


	PORTA = byte;
	_delay_ms(1);

	PORTB |=  (1<<E);
	_delay_ms(1);

	PORTB &=~ (1<<E);
	_delay_ms(1);

	

//	PORTA = (byte<<4);        // раскаментирую для 4 битного подключения

//	_delay_ms(1);
//	PORTB |=  (1<<E);
//	_delay_ms(1);
//	PORTB &=~ (1<<E);
//	_delay_ms(1);

	DDRA = 0;
}

void LCD_STRING(unsigned char *message )
{
	unsigned char i=0;

	while( (i<16) & (message[i]!=0) )
	{	
		LCD( DATA , message[i] );
		i++;
	}

}
