onewire.c
/*
程序说明: 单总线驱动程序
软件环境: Keil uVision 4.10
硬件环境: CT107单片机综合实训平台(外部晶振12MHz) STC89C52RC单片机
日 期: 2011-8-9
*/
#include "onewire.h"
sbit DQ = P1^4; //单总线接口
//单总线延时函数
void Delay_OneWire(unsigned int t) //STC89C52RC
{
t = t*12;//iap15单片机1个时钟周期执行一个指令,51单片机12个时钟周期执行一个指令
//iap15比c51速度快12倍,所以*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;
}
float rd_temperature(void)
{
u8 low,high;
float temp;
init_ds18b20();
Write_DS18B20(0xcc);//跳过ROM区
Write_DS18B20(0x44);//开始温度转换
//这里没有使用延时等待转换完成,读取暂存区是上次的结果,刚开始上电是会显示85
init_ds18b20();
Write_DS18B20(0xcc);//跳过ROM区
Write_DS18B20(0xbe);//读取暂存区数据
low = Read_DS18B20();
high = Read_DS18B20();
temp = (high<<8|low) * 0.0625;
return temp;
}
onewire.h
#ifndef __ONEWIRE_H
#define __ONEWIRE_H
#include "sys.h"//可以换成<stc15f2k60s2>
float rd_temperature(void);
#endif
mian.c
#include "sys.h"
#include "tim.h"
#include "smg.h"
#include "key.h"
#include "onewire.h"
HextoBin led_ctrl,uln_ctrl;//LED,蜂鸣器,继电器控制变量
u16 cnt_key;//三行按键扫描标志位,1ms加一次
u16 cnt_temperature;//温度读取标志位,1ms加一次
u32 temperature=850000;
u8 num=100;
void System_Init()
{
led_ctrl.hex = 0xff;
Device_Ctrl(0x80,led_ctrl.hex);//关闭LED灯
uln_ctrl.hex = 0x00;
Device_Ctrl(0xa0,uln_ctrl.hex);//关闭蜂鸣器和继电器
}
void SMG_Process()//数码管处理函数
{
smg_buf[0] = smg_duanxuan[temperature/100000];
smg_buf[1] = smg_duanxuan[temperature/10000%10]|0x80;
smg_buf[2] = smg_duanxuan[temperature/1000%10];
smg_buf[3] = smg_duanxuan[temperature/100%10];
smg_buf[4] = smg_duanxuan[temperature/10%10];
smg_buf[5] = smg_duanxuan[temperature%10];
smg_buf[6] = smg_duanxuan[0];
smg_buf[7] = smg_duanxuan[0];
}
void KEY_Process()//按键处理模块
{
if(cnt_key>=10)
{
cnt_key = 0;
KBD_ThreeLine();
if(Trig_KBD == 0x48)//s5
{
num++;
}
if(Trig_KBD == 0x88)//S4
{
num--;
}
}
}
void DS18B20_Process()
{
if(cnt_temperature>=100)
{
cnt_temperature = 0;
temperature = rd_temperature()*10000;
}
}
void main()
{
System_Init();
while(temperature>=800000)
{
temperature = rd_temperature()*10000;
}
Timer2Init();
while(1)
{
SMG_Process();
DS18B20_Process();
}
}
void Timer2() interrupt 12
{
cnt_key++;cnt_temperature++;
display_bit();
KEY_Process();
}