//mega8 7.3728MHz gcc编译通过,_delay_us(us) _delay_ms(ms)调用库函数
//初始化把dq设置为输出
#define ds18b20_dq PC5
#define set_ds18b20_dq_ddr() DDRC|=1<<ds18b20_dq
#define set_ds18b20_dq() PORTC|=1<<ds18b20_dq
#define clr_ds18b20_dq() PORTC&=~(1<<ds18b20_dq)
#define clr_ds18b20_dq_ddr() DDRC&=~(1<<ds18b20_dq)
#define in_ds18b20_dq() PINC&(1<<ds18b20_dq)
#define ds18b20_read_rom 0x33
#define ds18b20_match_rom 0x55
#define ds18b20_skip_rom 0xcc
#define ds18b20_search_rom 0xf0
#define ds18b20_alarm_search_rom 0xec
#define ds18b20_write_ram 0x4e
#define ds18b20_read_ram 0xbe
#define ds18b20_copy_ram 0x48
#define ds18b20_convert_tem 0x44
#define ds18b20_eecall_eeprom 0xb8
#define ds18b20_read_power_supply 0xb4
void reset_ds18b20(void)
{
clr_ds18b20_dq();
_delay_us(198);//100us
_delay_us(198);//100us
_delay_us(198);//100us
_delay_us(198);//100us
set_ds18b20_dq();
_delay_us(38);//20us
}
void ack_ds18b20(void)
{
while(in_ds18b20_dq());
while(!(in_ds18b20_dq()));
_delay_us(38);//20us
}
uchar read_ds18b20(void)
{
uchar data=0;
uchar i=0;
for(i=0;i<8;i++)
{
data>>=1;
clr_ds18b20_dq();
_delay_us(1);//1us
set_ds18b20_dq();
_delay_us(2);//2us
if(in_ds18b20_dq()) data|=0x80;
_delay_us(118);//60us
}
return(data);
}
void write_ds18b20(uchar data)
{
uchar i=0;
for(i=0;i<8;i++)
{
if(data&0x01){
clr_ds18b20_dq();
_delay_us(14);//8us
set_ds18b20_dq();
_delay_us(108);//55us
}
else
{
clr_ds18b20_dq();
_delay_us(108);//55us
set_ds18b20_dq();
_delay_us(14);//8us
}
data>>=1;
}
}
void convert_ds18b20(void)
{
reset_ds18b20();
ack_ds18b20();
_delay_ms(1);
write_ds18b20(ds18b20_skip_rom);
write_ds18b20(ds18b20_convert_tem);
}
void read_temperature(void)
{
reset_ds18b20();
ack_ds18b20();
_delay_ms(1);
write_ds18b20(ds18b20_skip_rom);
write_ds18b20(ds18b20_read_ram);
temperature_low=read_ds18b20();
temperature_high=read_ds18b20();
}