如图,在测试ds18b20时 ,温度跳到25.0以后自动变成00.4,然后01.4,02.4,03.4
代码如下
#include<reg52.h> #include<intrins.h> typedef unsigned char u8; typedef unsigned int u16; sbit ds=P2^2; sbit ser=P2^7; sbit srclk=P2^6; sbit rclk=P2^5; bit flag; unsigned char code smgduan[]={0x3f, 0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f, 0x77,0x7c,0x39,0x5e,0x79,0x71}; unsigned char code smgwei[]={0xfe, 0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f}; void delayms(u16 n); void TempDelay(u16 us); void send_595(u8 dat); void ds_reset() { ds=1; _nop_(); ds=0; TempDelay(80);//520us ds=1; TempDelay(5); if(ds==0) flag=1; else flag=0; TempDelay(20); ds=1; } bit ds_read_bit() { bit dat; ds=0; _nop_(); _nop_(); ds=1; _nop_(); dat=ds; TempDelay(12); return dat; } u8 ds_read_byte() { u8 i,j,value; for(i=0;i<8;i++) { j=ds_read_bit(); value=(j<<7)|(value>>1); } return value; } void ds_write_byte(u8 dat) { u8 i,onebit; for(i=0;i<8;i++) { onebit=dat&0x01; if(onebit) //?1 { ds=0; TempDelay(1); ds=1; _nop_(); } else //?0 { ds=0; TempDelay(11); ds=1; _nop_(); } dat>>=1; } } u8 get_temperature() { u16 temp,temp1; u8 a,b; ds_reset(); ds_write_byte(0xcc); ds_write_byte(0x44); ds_reset(); ds_write_byte(0xcc); ds_write_byte(0xbe); a=ds_read_byte(); b=ds_read_byte(); temp=b; temp<<=8; temp|=a; temp1 = temp*0.0625; temp=temp1*10+0.5; return temp ; } void main() { u16 j; while(1){ j=get_temperature(); send_595(smgwei[0]); send_595(smgduan[j/1000]); rclk=0; rclk=1; delayms(1); send_595(smgwei[1]); send_595(smgduan[j%1000/100]); rclk=0; rclk=1; delayms(1); send_595(smgwei[2]); send_595(smgduan[j%100/10]); rclk=0; rclk=1; delayms(1); send_595(smgwei[3]); send_595(0X80); rclk=0; rclk=1; delayms(1); send_595(smgwei[4]); send_595(smgduan[j%10]); rclk=0; rclk=1; delayms(1); send_595(smgwei[5]); send_595(smgduan[12]); rclk=0; rclk=1; delayms(1); } } void delayms(u16 n) { u8 i; while(n--) for(i=0;i<113;i++); } void TempDelay(u8 us) { while(us--); } void send_595(u8 dat) { u8 i; for(i=0;i<8;i++) { if(dat&0x80) ser=1; else ser=0; srclk=0; srclk=1; dat=dat<<1; } }