51单片机的温度模块:main.c:#include"reg52.h" //头文件
#include"ds18b20.h" // 温度模块驱动
#include"intrins.h" //移位操作头文件
sfr AUXR=0x8E;
unsigned char discode[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff,0xbf,0xc6}; //数码管显示字节码
unsigned char disbuff[]={10,10,10,10,10,10,10,10}; //字节码指针
unsigned char bitCom=0; // 位选指针
unsigned char temp=0; //设置温度变量
void Timer0Init(); //初始化定时器
void initSystem() //初始化系统
{
P2=((P2&0x1f)|0xA0); //关蜂鸣器
P0=0x00;
P2&=0x1f;
Timer0Init();
EA=1; //开系统总中断
}
void display() //数码管显示
{
P2=((P2&0x1f)|(0xe0)); //段选,消影
P0=0xff;
P2&=0x1f;
P2=((P2&0x1f)|(0xc0)); //位选
P0=1<8) bitCom=0; /当扫描完一遍时,在从头开始扫
}
unsigned char readTemp() //温度读取
{
unsigned char low,high;
unsigned char temp;
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
Delay_OneWire(200);
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
low=Read_DS18B20(); //分高低位读取
high=Read_DS18B20();
temp=high<<4; //高位左移四位
temp|=(low>>4); //低位右移四位再和高位左移后的结果相与
return temp;
}
void main()
{
initSystem();
while(1)
{
temp=readTemp();
disbuff[0]=10;
disbuff[1]=10;
disbuff[2]=10;
disbuff[3]=10;
disbuff[4]=10;
disbuff[5]=temp/10;
disbuff[6]=temp%10;
disbuff[7]=12;
}
}
void f1() interrupt 1
{
display(); //每1ms显示1次
}
void Timer0Init(void) //1毫秒@11.0592MHz
{
AUXR |= 0x80; //定时器时钟1T模式
TMOD &= 0xF0; //设置定时器模式
TL0 = 0xCD; //设置定时初值
TH0 = 0xD4; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0 = 1; //开定时器0中断
}
比赛提供的驱动:
ds18b20.h:
#ifndef __DS18B20__H_
#define __DS18B20__H_
#include "reg52.h"
#define OW_SKIP_ROM 0xcc
#define DS18B20_CONVERT 0x44
#define DS18B20_READ 0xbe
//IC引脚定义
sbit DQ = P1^4;
//函数声明
void Delay_OneWire(unsigned int t);
void Write_DS18B20(unsigned char dat);
bit Init_DS18B20(void);
unsigned char Read_DS18B20(void);
unsigned char rd_temperature(void);
#endif
ds18b20.c:/*
程序说明: 单总线驱动程序
软件环境: Keil uVision 4.10
硬件环境: CT107单片机综合实训平台
日 期: 2011-8-9
*/
#include "ds18b20.h"
//单总线延时函数
void Delay_OneWire(unsigned int t)
{
unsigned char i;
while(t--)
{
for(i=12;i>0;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);
}
return dat;
}
unsigned char rd_wendu()
{
unsigned char low,high;
unsigned char temp;
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
Delay_OneWire(200);
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0xBE);
low = Read_DS18B20();
high = Read_DS18B20();
temp = high<<4;
temp |= low>>4;
return temp;
}