当前位置:
文档之家› 蓝桥杯驱动程序带注释--DS18B20温度采集
蓝桥杯驱动程序带注释--DS18B20温度采集
1
DS18B20.h
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
#ifndef _DS18B20_H #define _DS18B20_H #include "stc15f2k60s2.h" #include "intrins.h" //注意添加头文件 sbit DQ = P1^4; //单总线接口
//单总线延时函数,针对1T单片机修改延时函数 //t*6us延时,可以视情况修改 void Delay_OneWire(unsigned int t) { unsigned char i; while(t--) { for(i=0;i<12;i++); } } //DS18B20芯片初始化 bit Init_DS18B20(void) { bit initflag = 0; DQ = 1; Delay_OneWire(12); DQ = 0; Delay_OneWire(80); DQ = 1; Delay_OneWire(10); initflag = DQ; Delay_OneWire(5); return initflag; } //通过单总线向DS18B20写一个字节 void Write_DS18B20(unsigned char dat) { unsigned char i; for(i=0;i<8;i++) { DQ = 0; DQ = dat&0x01; Delay_OneWire(5); DQ = 1; dat >>= 1; } Delay_OneWire(5); } //从DS18B20读取一个字节 unsigned char Read_DS18B20(void) { unsigned char i; unsigned char dat; for(i=0;i<8;i++) { DQ = 0; dat >>= 1; DQ = 1; if(DQ) { dat |= 0x80; } Delay_OneWire(5); }
DS18B20.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
return dat; } void Start18B20(void) { Init_DS18B20(); Write_DS18B20(0xCC); //跳过ROM操作 Write_DS18B20(0x44); //启动一次温度转换 } /*注意*/ unsigned char GetTemp(void) { unsigned char temp, LSB, MSB; Init_DS18B20(); Write_DS18B20(0xCC); //跳过ROM操作 Write_DS18B20(0xBE); //发送读命令 LSB = Read_DS18B20(); //读温度值的高字节 MSB = Read_DS18B20(); //读温度值的低字节 temp = (LSB>>4) | (MSB<<4); return temp; } #endif
2