www.pudn.com > TG12864.rar > DS1820.C
#include#include #define uchar unsigned char #define SomeNOP(); _nop_();_nop_();_nop_();_nop_(); //定义空指令 sbit DQ =P2^7; //定义数据端口 bit flag; unsigned char temp1,temp2; /*************************温度传感器子函数*********************/ // 延时480us void Delay_480() { uchar i,j; for(i=0;i<100;i++) { for(j=0;j<9;j++); } } // 延时15us void Delay_15() { uchar i; for(i=0;i<28;i++); } //延时60us void Delay_60() { uchar j; for(j=0;j<111;j++); } ///延时100ms void Delay_100() { uchar i,j,k; for(i=0;i<50;i++) { for(j=0;j<100;j++) { for(k=0;k<37;k++); } } } //延时10us void Delay_10() { uchar i; for(i=0;i<18;i++); } //写bit 0 void Write_0() { DQ=1; _nop_(); DQ=0; Delay_15(); //置总线为地电平并保持至少15us, Delay_15(); Delay_15(); Delay_15(); //yan shi 45us ,等待1820对总线数据采样 DQ=1; //数据线置为高电平完成写0 操作 _nop_(); _nop_(); } //写bit 1 void Write_1() //{ 延时 { DQ=1; _nop_(); DQ=0; _nop_(); // _nop_(); 风 // _nop_(); 延时 _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); DQ=1; // Delay_15(); 延延时延时除恶我 时 Delay_15(); Delay_15(); //延时45us等待1820对总线数据采样 Delay_15(); } ///读取数据位 bit Read() { bit b; DQ=1; _nop_(); DQ=0; _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); DQ=1; Delay_10(); b=DQ; //读取一位数据 Delay_15(); Delay_15(); Delay_15(); DQ=1; //读操作完成 return b ; } ///复位函数 void Reset() { uchar i; DQ=1; _nop_(); DQ=0; Delay_480(); DQ=1; Delay_60(); if(DQ==0) flag=1; //产生存在脉冲 else flag=0; // 不产生存在脉冲 for(i=0;i<3;i++) Delay_60(); } ////*******单片机往1820写一个字节(byte) void Write_byte(byte) { uchar i; for(i=0;i<8;i++) { if(byte&0x01) //最低字节为1否? Write_1(); else Write_0(); byte=byte>>1; //字节右移一位 _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); //每个写周期至少应该有1微秒的时间间隔 } } /////从1820传感器读取一个字节 uchar Read_byte() { uchar i,j; bit c; j=0; for(i=0;i<8;i++) { c=Read(); if(c) j+=1; j=_cror_(j,1); //循环右移一位 _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); //每个读周期至少应该有1微秒的时间间隔 } return j; } /// 初始化温度传感器1820 void Init_1820() { Reset(); //复位总线 Write_byte(0xCC); //忽略ROM匹配操作 Write_byte(0x4E); //设置写模式 Write_byte(0x64); // 写温度上限为+100摄氏度 Write_byte(0x8a); //写温度下限为-10摄氏度 Write_byte(0x1f); //写温度计匹配寄存器 // Reset(); //操作完成 // Write_byte(0xcc); /// Write_byte(0x48); //保存设定值 /// Reset(); // Write_byte(0xcc); // Write_byte(0xb8); } //********获得温度值,2字节数据分别放在temp1,temp2 void Get_temp() { Reset(); Write_byte(0xCC); Write_byte(0x44); //温度转换命令 Delay_100(); //延时100毫秒 Reset(); Write_byte(0xCC); Write_byte(0xBE); //读取寄存器 temp2=Read_byte(); //度取第一个字节 temp1=Read_byte(); //读取第二个字节 Read_byte(); Read_byte(); Read_byte(); Read_byte(); Read_byte(); Read_byte(); Read_byte(); //读取第九个字节 //do{ // Reset();}while(!flag); temp1=temp1<<4; temp1+=(temp2&0xF0)>>4; // 获得温度值整数部分 temp2=(temp2&0x0F)?5:0; // 获得温度值小数部分 } /***********************void main(void)****************************/ void main() { // P0M1=0x00; // P0M2=0x00; P2M1=0x00; P2M2=0x00; //设置端口P2^7双向输入输出口 Init_1820(); //初始化温度传感器1820 Get_temp(); //获得温度值,2字节数据分别放在temp1,temp2 while(1); }