main.c
#include "reg52.h"
#include "onewire.h"
unsigned int a,b,c;
unsigned int Temp;
unsigned char code duanma[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff};
unsigned char code duanmadot[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};
void SelectHC573(unsigned char n){
switch(n){
case 4:
P2 = (P2 & 0x1f) | 0x80;
break;
case 5:
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6:
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7:
P2 = (P2 & 0x1f) | 0xe0;
break;
}
}
void Display(unsigned char pos,unsigned char value){
SelectHC573(7);
P0 = 0xff;
SelectHC573(6);
P0=0x01<<pos;
SelectHC573(7);
P0=value;
}
void SystemInit(){
SelectHC573(4);
P0 = 0xff;
SelectHC573(5);
P0 = 0x00;
}
void delaysmg(unsigned int t){
while(t--);
}
void show(){
a=Temp/100;
b=(Temp%100)/10;
c=Temp%10;
Display(5,duanma[a]);
delaysmg(500);
Display(6,duanmadot[b]);
delaysmg(500);
Display(7,duanma[c]);
delaysmg(500);
Display(0,duanma[10]);//避免最后一位过亮
delaysmg(500);
Display(1,duanma[10]);
delaysmg(500);
Display(2,duanma[10]);
delaysmg(500);
Display(3,duanma[10]);
delaysmg(500);
Display(4,duanma[10]);
delaysmg(500);
}
void Read_Temperature()
{
unsigned char LSB,MSB ;
init_ds18b20();
Write_DS18B20(0xCC);
Write_DS18B20(0x44);
init_ds18b20();
Write_DS18B20(0xCC);
Write_DS18B20(0xBE);
LSB = Read_DS18B20();
MSB = Read_DS18B20();
Temp = MSB;
Temp = (Temp<<8)|LSB;//将LSB和MSB整合成为一个16位的整数
if((Temp & 0xf800) == 0x0000)
{
Temp >>= 4;
Temp = Temp*10;
Temp = Temp + (LSB&0x0f)*0.625;
}
}
void main(){
SystemInit();
while(1){
Read_Temperature();
show();
}
}
onewire.c
/*
程序说明: 单总线驱动程序
软件环境: Keil uVision 4.10
硬件环境: CT107单片机综合实训平台(外部晶振12MHz) STC89C52RC单片机
日 期: 2011-8-9
*/
#include "reg52.h"
sbit DQ = P1^4; //单总线接口
//单总线延时函数
void Delay_OneWire(unsigned int t) //STC89C52RC
{
t=t*12;
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;
}
onewire.h
#ifndef __ONEWIRE_H
#define __ONEWIRE_H
void Write_DS18B20(unsigned char dat);
unsigned char Read_DS18B20(void);
bit init_ds18b20(void);
#endif
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)