#define F_CPU 16000000					// frekvence krystalu
#include <math.h>
#include <avr/io.h>						// I/O vstupy ATmega16
#include <util/delay.h>					// knihovna easu
#include <avr/interrupt.h>
#define LCD
#include "mojelib1.h"					// knihovna pro LCD
#include "twi_lib.h"					// knihovna i2c/twi

#define k30_W 0xD0	//write k30 adress
#define k30_R 0xD1 //read k30 adress

char buffer1[16];
int co2_value;
int byte1;
int byte2;
int byte3;
int byte4;


int main (void)
{
	i2c_init();

	while(1)
	{
		DDRB=0xff;
		PORTB = 0x00;
		_delay_ms(200);

		i2c_start_wait(k30_W);
		i2c_write(0x22);
		i2c_write(0x00);
		i2c_write(0x08);
		i2c_write(0x2A);
		i2c_stop();

		_delay_ms(10);

		i2c_rep_start(k30_R);

		byte1=i2c_readAck();    //precti byte 1 az 4
		byte2=i2c_readAck();
		byte3=i2c_readAck();
		byte4=i2c_readNak();
		i2c_stop();

		co2_value = 0;              //spojeni bytu 2 a 3 da koncentraci CO2
		co2_value |= byte2 & 0xFF;
		co2_value = co2_value << 8;
		co2_value |= byte3 & 0xFF;

		TWCR =0x00;//vypne i2c

		//dtostrf(co2_value,5 ,2, buffer1);
		itoa(co2_value, buffer1, 10);

		DDRC = 0xff;//c je vystup
		PORTC = 0b11000010; //povoleni lcd

		init_lcd();			//inicializace LCD
		_delay_ms(5);
		cls();				// smazání LCD displeje
		_delay_ms(5);


		line_1();
		lcd_text("CO2:");

		line_2();
		lcd_puts(buffer1);
		gotoxy(2,14);
		lcd_text("ppm");
		_delay_ms(500);
		_delay_ms(500);
		_delay_ms(500);
		_delay_ms(500);
	}
	return 1;
}


