底层代码:onewire.c
#include <REGX52.H>
sbit DQ=P1^4;
void Delay_OneWire(unsigned int t)
{
while(t--){
}
}
//
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
DQ = 0;
DQ = dat&0x01;
Delay_OneWire(50);
DQ = 1;
dat >>= 1;
}
Delay_OneWire(50);
}
//
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(50);
}
return dat;
}
//
bit init_ds18b20(void)
{
bit initflag = 0;
DQ = 1;
Delay_OneWire(120);
DQ = 0;
Delay_OneWire(800);
DQ = 1;
Delay_OneWire(100);
initflag = DQ;
Delay_OneWire(50);
return initflag;
}
因为开发平台与底层代码有出入,所以需要自己修改代码,将延时函数都乘10倍
onewire.h头文件
DS18B20.c函数:(主要记住核心流程)
#include "reg52.h"
#include "smg.h"
#include "onewire.h"
#include "absacc.h"
unsigned int temp=0;
//不显示小数位
void DisplaySMG()
{
DisPlaySMG_bit(7,SMGNoDot_CA[temp%10]);
DelaySMG(100);
DisPlaySMG_bit(6,SMGNoDot_CA[temp/10]);
DelaySMG(100);
DisPlaySMG_bit(5,0xff);
DelaySMG(100);
DisPlaySMG_bit(4,0xff);
DelaySMG(100);
DisPlaySMG_bit(3,0xff);
DelaySMG(100);
DisPlaySMG_bit(2,0xff);
DelaySMG(100);
DisPlaySMG_bit(1,0xff);
DelaySMG(100);
DisPlaySMG_bit(0,0xff);
DelaySMG(100);
DisPlay_ALL(0xff);
}
void Delay(unsigned int t)
{
while(t--)
{
DisplaySMG();
}
}
void Read_Temp()
{
unsigned char LSB,MSB;
//复位
init_ds18b20();
//写入字节,跳出ROM指令
Write_DS18B20(0xCC);
//写入字节,进行温度转换
Write_DS18B20(0x44);
//进行动态延时
Delay(1000);
//复位
init_ds18b20();
//写入字节,跳出ROM指令
Write_DS18B20(0xCC);
//写入字节,读取高速暂存器
Write_DS18B20(0xBE);
//读取第0字节,温度数据的LSB
LSB=Read_DS18B20();
//读取第1字节,温度数据的MSB
MSB=Read_DS18B20();
// //复位,表示读取数据结束
// init_ds18b20();
//整合成16位数据
temp=MSB;
temp<<=8;
temp=temp|LSB;
temp>>=4;//把小数位挪走
// temp=temp*0.0625;
}
void main()
{
XBYTE[0X8000]=0XFF;
while(1)
{
Read_Temp();
DisplaySMG();
}
}
smg模块:
smg.c文件
//存储器模式
#include "absacc.h"
//延迟函数
void DelaySMG(unsigned char t)
{
while(t--);
}
void DisPlaySMG_bit(unsigned char pos,unsigned char value)
{
XBYTE[0XE000]=0XFF;//消影
XBYTE[0XC000]=0X01<<pos;
XBYTE[0XE000]=value;
}
void DisPlay_ALL(unsigned char dat)
{
XBYTE[0XC000]=0XFF; //所有位置都选上
XBYTE[0XE000]=dat;
}
smg.h函数
#ifndef RR_SMG_H
#define RR_SMG_H
code unsigned char SMGNoDot_CA[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
code unsigned char SMGDot_CA[10]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};
void DelaySMG(unsigned char t);
void DisPlaySMG_bit(unsigned char pos,unsigned char value);
void DisPlay_ALL(unsigned char dat);