温度传感器,ds18b20
#include <reg52.h> #include <intrins.h> #define NOP() _nop_() #define uchar unsigned char #define uint unsigned int unsigned int temp; float f_temp; sbit ds = P2^2; sbit dula=P2^6; //数码管段选线 sbit wela=P2^7; //数码管位选线 unsigned char code table[]={ 0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f, 0xbf,0x86,0xdb,0xcf, 0xe6,0xed,0xfd,0x87, 0xff,0xef}; //不带小数点的编码 void delay15us(); void delayUS(int us); //us=50为600us /* 当us=1时,延迟时间为30us, 当us=2时,延迟时间为43us 当us=3时,延迟时间为56us, 可以看出基本的调用时间为17us,每增加一次循环增加13us, */ void reset(); void writeBit(char dat); void writeByte(unsigned char val); char readBit(void); char readByte(void); void convert(void); unsigned int getTemperature(void); void display(unsigned char num,unsigned char dat); void dis_temp(unsigned int t); void main(void) { dula=0; wela=0; while(1) { convert(); dis_temp(getTemperature()); } } void delayUS(int us) { while(us--); // NOP(); } void delay15us() { NOP();NOP();NOP();NOP();NOP();NOP(); NOP();NOP();NOP();NOP();NOP(); } void reset() { ds = 0; delayUS(37);//480us ds = 1; delayUS(37);//对照着ds18b20 复位时序图写 } void writeBit(unsigned char dat) { ds = 0; delay15us(); if(dat == 1) ds = 1; delay15us(); delay15us(); delay15us(); ds = 1; } void writeByte(unsigned char val) { unsigned char dat; int i; for(i = 8; i > 0; i--) { dat = val & 0x01; writeBit(dat); val = val>>1; } } char readBit(void) { char dat; ds = 0; NOP(); ds = 1; //应该在0~15us的时间内,ds18b20都会在数据线上写数据,可以再这之后写几个nop(); delay15us(); dat = ds; delayUS(3); return dat; } char readByte(void) { uchar i,temp,dat; dat=0; for(i=1;i<=8;i++) { temp=readBit(); //在读暂存器时,数据以位0为最低有效位从单总线移出 dat=(temp<<7)|(dat>>1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里 } return(dat); } void convert(void) { reset(); writeByte(0xCC); writeByte(0x44); } unsigned int getTemperature(void) { uchar LSB, MSB; reset(); writeByte(0xCC); writeByte(0xBE); LSB = readByte(); MSB = readByte(); temp = MSB; temp = (temp<<8) | LSB; f_temp=temp*0.0625; //温度在寄存器中为12位 分辨率位0.0625° temp=f_temp*10+0.5; //乘以10表示小数点后面只取1位,加0.5是四舍五入 f_temp=f_temp+0.05; return temp; //temp是整型 } void display(uchar num,uchar dat) { uchar i; dula=0; P0=table[dat]; dula=1; dula=0; wela=0; i=0XFF; i=i&(~((0X01)<<(num))); P0=i; wela=1; wela=0; delayUS(150); } void dis_temp(uint t) { uchar i; i=t/100; display(0,i); i=t%100/10; display(1,i+10); i=t%100%10; display(2,i); }