📄 ds18b20(c8051f340).c
字号:
/////////////////////////////////////
// Generated Initialization File //
/////////////////////////////////////
#include "C8051F340.h"
#include "INTRINS.H"
#define uchar unsigned char
#define uint unsigned int
void Write_Byte(uchar a);
void Tx_date(uchar);
sbit DQ=P1^3;
uchar templ,temph;
uchar ID[8]={0x28,0xf0,0xd8,0x6f,0x01,0x00,0x00,0xad};
//uchar NewID[8];
void Delay(uint d)
{
while(d--);
}
/*Delay(1)=22/12us; Delay(18)=10us;没变化2,变化1us;Delay(108)=45us;{Delay(87)=45us,Delay(118)=60us;}for()语句大概6.17个周期
,不加前三个,Delay(1000)=500us;for(2000)=1s}
实际Delay(1)=1.31us;Delay(2)=1.68;Delay(15)=6.44us;Delay(10)=4.61;Delay(18)=7.55;Delay(20)=8.2;Delay(30)=12us;Delay(87)=32.89us;Delay(118)=44.29us;Delay(160)=60us;Delay(1000)
=368.41us;Delay(1500)=552.16us;Delay(1360)=500us;
*/
void init(void)
{
uchar i; //60-240us来产生应答信号,主机收到应答脉冲后表明总线上有器件
bit DS_flag;
DS_flag = 1;
DQ = 1;
Delay(1);
DQ = 0;
Delay(1360); //延时480us-900us
DQ = 1; //产生上升沿
Delay(90);//拉高总线33us,等待18B20响应
while(DQ);
while(~DQ);
Delay(1000); //360us
Write_Byte(0x55); //符合ROM
for(i=0;i<8;i++)
Write_Byte(ID[i]);
}
void Write_Byte(uchar b) //写字节数据
{
uchar j;
DQ = 1;
Delay(1);
for(j=0;j<8;j++)
{
DQ = 0;
Delay(20); //delay 8us
DQ = b&0x01;
Delay(160); //60 us
b= b>>1;
DQ = 1;
Delay(1);
}
}
uchar Read_Byte(void) //读取一个字节
{
uchar i,b;
b = 0;
DQ = 1;
Delay(1); //保持至少1us
for(i=0;i<8;i++)
{
DQ = 0;
Delay(10); //延时4.5us
DQ = 1;
Delay(10);
b= b>>1;
if(DQ == 1) b = b+0x80;
Delay(160);//60us
}
return b;
}
void Convert_temp(void)
{
uint d;
init();
Write_Byte(0x44);// 启动温度转换
for(d=2000;d>0;d--)
Delay(1360); //延时1s,大于转换时间750ms
}
void Get_temp(void)
{
init(); // 初始化
Write_Byte(0xbe);//读温度命令
templ=Read_Byte();// 读取低位温度
temph=Read_Byte();// 读取高位温度
}
void Tx_date(uchar a)
{
SBUF0=a;
while(TI0==0);
TI0=0;
}
void Read_id(uchar *a)
{
uint i;
init();
Write_Byte(0x33);//读ROM
for(i=0;i<8;i++)
*a++=Read_Byte();
}
void main (void)
{
PCA0MD &= ~0x40;
OSCICN = 0x83;
XBR0 = 0x09;
XBR1 = 0x40;
SCON0 = 0x10;
TCON = 0x40;
TMOD = 0x21;
CKCON = 0x01;
TL1 = 0x64;
TH1 = 0x64;
//Read_id(NewID);
while(1)
{
Convert_temp();
Get_temp();
//templ=0x128;
//temph=0x01;
Tx_date(templ);
Tx_date(temph);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -