以下为本人代码:
主函数:
#include "reg52.h"
#include "absacc.h"
#include "onewire.h"
//==========================DS18B20函数声明
void Delay_OneWire(unsigned int t);
void Write_DS18B20(unsigned char dat);
unsigned char Read_DS18B20(void);
bit init_ds18b20(void);
unsigned char rd_temperature(void);
void SMG_ShowDynamic();
//==========================
unsigned int temp=0;
unsigned char code SMG_NoDot[18]={0xc0,0xf9,
0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,
0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};//²»´øСÊýµã0~F+¶ÌºáÏߺ͵ã
unsigned char code SMG_Dot[10]={0x40,0x79,
0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};//´øСÊýµã0.~9.
void DelaySMG(unsigned int t)
{
while(t--);
}
void SMG_ShowStatic(unsigned char pos,unsigned char dat)
{
XBYTE[0xe000] = 0xff;
XBYTE[0xc000] = 0x01<<pos;
XBYTE[0xe000] = dat;
}
void DisplaySMG_All(unsigned char dat)
{
XBYTE[0xc000] = 0xff;
XBYTE[0xe000] = dat;
}
//4567/1000=4
//(4567%1000)=567 567/100=5
//4567%100=67 67/10=6
//4567%10=7
void SMG_ShowDynamic()
{
SMG_ShowStatic(7,SMG_NoDot[temp%10]);
DelaySMG(100);
SMG_ShowStatic(6,SMG_NoDot[(temp%100)/10]);
DelaySMG(100);
SMG_ShowStatic(5,SMG_Dot[(temp%1000)/100]);
DelaySMG(100);
SMG_ShowStatic(4,SMG_NoDot[temp/1000]);
DelaySMG(100);
SMG_ShowStatic(3,0xff);
DelaySMG(100);
SMG_ShowStatic(2,0xff);
DelaySMG(100);
SMG_ShowStatic(1,0xff);
DelaySMG(100);
SMG_ShowStatic(0,0xff);
DelaySMG(100);
DisplaySMG_All(0xff);
}
void DelayDS18B20(unsigned int t)
{
t=t*12;
while(t--)
{
SMG_ShowDynamic();
}
}
void ServiceDS18B20()
{
unsigned char LSB,MSB;
init_ds18b20();
SMG_ShowDynamic();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
SMG_ShowDynamic();
DelayDS18B20(1000);
SMG_ShowDynamic();
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
SMG_ShowDynamic();
init_ds18b20();
LSB = Read_DS18B20();
MSB = Read_DS18B20();
temp = MSB;
temp = (temp<<8) | LSB;
if((temp & 0xf800)== 0x0000)
{
temp = temp>>4;
temp = temp*100;
temp = temp + (LSB&0x0f)*6.25;
}
SMG_ShowDynamic();
}
void main()
{
while(1)
{
ServiceDS18B20();
SMG_ShowDynamic();
}
}
单总线底层驱动:
#include "onewire.h"
//单总线函数专用延时
void Delay_OneWire(unsigned int t)
{
t=12*t;
while(t--);
}
//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);
}
return dat;
}
//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;
}
单总线头文件:
#ifndef __ONEWIRE_H
#define __ONEWIRE_H
#include "reg52.h"
void Delay_OneWire(unsigned int t);
sbit DQ = P1^4;
void Write_DS18B20(unsigned char dat);
unsigned char Read_DS18B20(void);
bit init_ds18b20(void);
unsigned char rd_temperature(void);
#endif
未完待续……