AVR单片机 ds18b20 gcc 源程序
扫描二维码
随时随地手机看文章
//mega8 7.3728MHzgCC编译通过,_delay_us(us) _delay_ms(ms)调用库函数 #define clr_ds18b20_dq() PORTC&=~(1<
//初始化把dq设置为输出
#define ds18b20_dq PC5
#define set_ds18b20_dq_ddr() DDRC|=1<
#define ds18b20_read_rom0x33
#define ds18b20_match_rom0x55
#define ds18b20_skip_rom0xcc
#define ds18b20_search_rom0xf0
#define ds18b20_alarm_search_rom0xec
#define ds18b20_write_ram0x4e
#define ds18b20_read_ram0xbe
#define ds18b20_copy_ram0x48
#define ds18b20_convert_tem0x44
#define ds18b20_eecall_eeprom0xb8
#define ds18b20_read_power_supply0xb4
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();
}