⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 18b20.h

📁 16个单片机c语言实验程序
💻 H
字号:
//DS18B20连接在端口C的第7引脚

//设置成输入
#define DQ_INPUT DDRC &= ~(1 << PC7)    
//设置成输出
#define DQ_OUT DDRC |= (1 << PC7)    
//设置成低电平
#define DQ_LO PORTC &= ~(1 << PC7)  
//设置成高电平
#define DQ_HI PORTC |= (1 << PC7)   
//读出
#define DQ_R PINC & (1 << PC7)      

//中断标志
unsigned char init_f;     

//延时函数
void s_10us(unsigned int ms)
{
    unsigned int aa;
	for(;ms>=1;ms--)
	{
	for(aa=0;aa<=17;aa++)
	{;}
	}
}	

//DS18B20复位
void ds1820_reset(void) 
{
 unsigned char i;
 //中断保护
 init_f = SREG;    
 //关中断
 CLI();      
 DQ_OUT;             //DS18B20初始化时序要求
 DQ_LO;
 s_10us(50);    //延时500us
 DQ_HI;
 DQ_INPUT;
 s_10us(8);     //延时80us
 i = DQ_R;
 s_10us(50);    //延时500us
 if (init_f & 0x80)  //恢复中断状态
  {   
  SEI();        
  }
}

//DS18B20字节读取
unsigned char ds1820_read_byte(void) 
{
 unsigned char i;
 unsigned char value = 0;
 //中断保护
 init_f = SREG;
 //关中断    
 CLI();      
 for (i = 8; i != 0; i--) {
  value >>= 1;       //存储读到的数据     左移一位
  DQ_OUT;
  DQ_LO;
  s_10us(1);
  DQ_HI;
  DQ_INPUT;
  s_10us(1);
  if (DQ_R) {
   value|=0x80;
   }
  s_10us(5);   //延时60us
  }
 if (init_f & 0x80) //恢复中断状态
 {   
  SEI();
  }
 return(value);
}

//DS18B20字节写入
void ds1820_write_byte(unsigned char value) 
{
 unsigned char i;
 //中断保护
 init_f = SREG;   
 //关中断 
 CLI();      
 for (i = 8; i != 0; i--) {
  DQ_OUT;
  DQ_LO;
  s_10us(1);
  if (value & 0x01) {
   DQ_HI;
   }
  s_10us(8);   //延时80us
  DQ_HI;     
  value >>= 1;
  }
 if (init_f & 0x80)//恢复中断状态
  {   
  SEI();
  }
}

//启动ds1820转换
void ds1820_start(void) 
{
 ds1820_reset();
 ds1820_write_byte(0xCC); //勿略ROM
 ds1820_write_byte(0x44); //启动转换
}

//读温度
unsigned int ds1820_read_temp(void)
 {
 unsigned int i;
 unsigned char buf[9];
 ds1820_reset();
 ds1820_write_byte(0xCC); //勿略ROM
 ds1820_write_byte(0xBE); //读温度
 for (i = 0; i < 9; i++) {
  buf[i] = ds1820_read_byte();
  }
 i = buf[1];
 i <<= 8;
 i |= buf[0];
 return i;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -