#include <avr/io.h> 
#include <util/delay.h> 
#include <avr/interrupt.h>
#include <stdio.h>
#include <stdint.h>
#include "1wire.h" 
#include "lcd.h" 

// *************************************************
// FCE: vycet a komunikace s cidlem teploty DS18B20
// INC: "1wire.h"
// DAT: 8.3.2012
// VER: 2 
// *************************************************	

uint8_t therm_reset()
{
	
	uint8_t i; 

	THERM_LOW(); 
	THERM_OUTPUT_MODE(); 
	_delay_us(480); 

	THERM_INPUT_MODE(); 
	_delay_us(60); 

	i=(THERM_PIN & (1<<THERM_DQ)); 
	_delay_us(420); 

	return i; 
} 


void therm_write_bit(uint8_t bit)
{ 

	THERM_LOW(); 
	THERM_OUTPUT_MODE(); 
	_delay_us(1); 

	if(bit) THERM_INPUT_MODE(); 

	_delay_us(60); 
	THERM_INPUT_MODE(); 
} 


uint8_t therm_read_bit(void)
{ 
	uint8_t bit=0; 

	THERM_LOW(); 
	THERM_OUTPUT_MODE(); 
	_delay_us(1); 

	THERM_INPUT_MODE(); 
	_delay_us(14); 

	if(THERM_PIN&(1<<THERM_DQ)) bit=1; 

	_delay_us(45); 
	return bit; 
} 


uint8_t therm_read_byte(void){ 
	uint8_t i=8, n=2; 
	while(i--){ 

		n>>=1; 
		n|=(therm_read_bit()<<7); 
	} 
	return n; 
} 


void therm_write_byte(uint8_t byte){ 
	uint8_t i=8; 
	while(i--){ 

		therm_write_bit(byte&1); 
		byte>>=1; 
	} 
} 

// vycet dat ze senzoru
void ThermRead(char *buffer1){ 

	uint8_t temperature[2]; 
	int8_t digit; 
	uint16_t decimal; 

	therm_reset(); 
	therm_write_byte(THERM_CMD_SKIPROM); 
	therm_write_byte(THERM_CMD_CONVERTTEMP); 

	while(!therm_read_bit()); 



	therm_reset(); 
	therm_write_byte(THERM_CMD_SKIPROM); 
	therm_write_byte(THERM_CMD_RSCRATCHPAD); 

	temperature[0]=therm_read_byte(); 
	temperature[1]=therm_read_byte(); 
	therm_reset(); 

	digit=temperature[0]>>4; 
	digit|=(temperature[1]&0xf)<<4; 

	decimal=temperature[0]&0x3; 
	decimal*=THERM_DECIMAL_STEPS_12BIT; 

//	sprintf(buffer1, "%+d.%04uČ", digit, decimal); // zobrazeni vystupniho retezce na displaji

	sprintf(buffer1, "Temp: %+dČ", digit);
	
}
