|
DS18B20温度传感器的protues模拟
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit wela = P2^0;
sbit dula = P2^1;
sbit IO_18B20 = P2^2; //DS18B20通信引脚
uint temp;
uchar code table[]={0x3f,0x06,0x05b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
void delay(uint ms) // ms延时函数 (AT89C51 @ 11.0592MHz)
{
unsigned int i;
unsigned char j;
for(i=0;i<ms;i++)
{
for(j=0;j<200;j++);
for(j=0;j<102;j++);
}
}
/* 软件延时函数,延时时间(t*10)us */
void DelayX10us(unsigned char t)
{
do {
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
} while (--t);
}
bit Get18B20Ack()
{
bit ack;
EA = 0;
IO_18B20 = 0;
DelayX10us(50);
IO_18B20 = 1;
DelayX10us(6);
ack = IO_18B20;
while(!IO_18B20);
DelayX10us(6);
EA = 1;
return ack;
}
void Write18B20(unsigned char dat)
{
unsigned char mask;
EA = 0;
for(mask=0x01; mask!= 0; mask<<=1)
{
IO_18B20 = 0;
_nop_();
_nop_();
//_nop_();
if((mask&dat) == 0)
IO_18B20 = 0;
else
IO_18B20 = 1;
DelayX10us(6);
IO_18B20 = 1;
_nop_();
_nop_();
_nop_();
}
EA = 1;
}
unsigned char Read18B20()
{
unsigned char dat;
unsigned char mask;
EA = 0;
for(mask=0x01; mask!=0; mask<<=1)
{
IO_18B20 = 0;
_nop_();
_nop_();
//_nop_();
IO_18B20 = 1;
_nop_();
_nop_();
_nop_();
if(!IO_18B20)
dat &= ~mask;
else
dat |= mask;
DelayX10us(6);
}
EA = 1;
return dat;
}
bit Start18B20()
{
bit ack;
ack = Get18B20Ack();
if(ack == 0)
{
Write18B20(0xCC);
Write18B20(0x44);
}
return ~ack;
}
bit Get18B20Temp(uint *temp)
{
bit ack;
unsigned char LSB, MSB;
ack = Get18B20Ack();
if(ack == 0)
{
Write18B20(0xCC);
Write18B20(0xBE);
LSB = Read18B20();
MSB = Read18B20();
*temp = ((int)MSB<<8) + LSB;
}
return ~ack;
}
void display(uint num)
{
uchar i;
for(i=0;i<6;i++)
{
//位选
P0 = ~(0x1<<i);
wela = 1;
wela = 0;
//段选
P0 = table[num%10];
dula = 1;
dula = 0;
num=num/10;
//去除前面为0的位
if(num==0)
{
i=6;
}
delay(3);
}
}
void main()
{
uint tmp;
while(1)
{
if(Start18B20())
{
if(Get18B20Temp(&temp))
{
tmp=temp;
tmp=tmp>>4;
tmp=tmp&0xFF;
display(tmp);
}
}
}
}
|
|