#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 MAX44009_W 0b10010100
#define MAX44009_R 0b10010101
// begin definition of slave addresses for MAX44009
#define INT_STATUS 0x00
#define INT_ENABLE 0x01
#define CONFIG_REG 0x02
#define HIGH_BYTE 0x03
#define LOW_BYTE 0x04
#define THRESH_HIGH 0x05
#define THRESH_LOW 0x06
#define THRESH_TIMER 0x07
// end definition of slave addresses for MAX44009

void getLightLevel(void); 
//long int Get2_x(unsigned char i);

char buffer1[16];
float lux;
int lowByte;
 int highByte;
 int exponent;
 int mantissa;
 

int main (void)
{
		sei();

		i2c_init();

	while (1)
	{
		DDRB=0xff;
		PORTB = 0x00;
		_delay_ms(200);
		
		getLightLevel(); //zmeri luxy

		TWCR =0x00;//vypne i2c
		dtostrf(lux, 6, 2, buffer1);

	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("Osvetleni:");
	
	line_2();
	
	lcd_puts(buffer1);
	gotoxy(2,14);
	lcd_text("lux");
	_delay_ms(100);
	}
	return 1;
}


void getLightLevel(void) 
{
 
i2c_start_wait(MAX44009_W);
i2c_write(HIGH_BYTE); 
i2c_rep_start(MAX44009_R);

highByte = i2c_readNak();

i2c_rep_start(MAX44009_W);
i2c_write(LOW_BYTE); 
i2c_rep_start(MAX44009_R);

lowByte=i2c_readNak();

i2c_stop();



 exponent = ((highByte & 0xF0) >> 4);// upper four bits of high byte register
 mantissa = ((highByte & 0x0F) << 4);// lower four bits of high byte register =
 // upper four bits of mantissa
 mantissa += lowByte & 0x0F; // lower four bits of low byte register =
 // lower four bits of mantissa

 lux = mantissa * pow(2, exponent) * 0.045;
}

/*long int Get2_x(unsigned char i) //vypocte dva na ntou
{
	long int uiData;
	uiData=2;
	i=i-1;
 while(i)
 	{
		uiData <<= 1;
		i--;
	 }
 return uiData;
}
*/
