
#include "reg51.h"
char disp[11] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x40};
char disp_dot[11] = {0xbf, 0x86, 0xdb, 0xcf, 0xe6, 0xed, 0xfd, 0x87, 0xff, 0xef, 0xc0};
sbit DQ = P1^3; // Define the communication pin
// 12MHz crystal frequency
void delay_18B20(unsigned int i)
{
while(i--);
}
// DS18B20 initialization function
void init_DS18B20(void)
{
unsigned char x = 0;
DQ = 1; // Release the bus
delay_18B20(8); // Small delay
DQ = 0; // Microcontroller pulls DQ low
delay_18B20(80); // Delay greater than 480us
DQ = 1; // Release the bus
delay_18B20(14);
x = DQ; // Check if the device is present
delay_18B20(20);
}
// Read a byte from DS18B20
unsigned char readOneChar(void)
{
unsigned char i = 0;
unsigned char dat = 0;
for (i = 8; i > 0; i--)
{
DQ = 0; // Pulse the line
dat >>= 1;
DQ = 1; // Release the line
if (DQ)
dat |= 0x80;
delay_18B20(4);
}
return(dat);
}
// Write a byte to DS18B20
void writeOneChar(unsigned char dat)
{
unsigned char i = 0;
for (i = 8; i > 0; i--)
{
DQ = 0;
DQ = dat & 0x01;
delay_18B20(5);
DQ = 1;
dat >>= 1;
}
}
// Read temperature from DS18B20
unsigned int readTemperature(void)
{
unsigned char a = 0;
unsigned char b = 0;
unsigned int t = 0;
init_DS18B20();
writeOneChar(0xCC); // Skip ROM
writeOneChar(0x44); // Start conversion
delay_18B20(100);
init_DS18B20();
writeOneChar(0xCC); // Skip ROM
writeOneChar(0xBE); // Read scratchpad
a = readOneChar();
b = readOneChar();
// Calculate temperature: (b * 256 + a) * 25 >> 2
t = (b * 256 + a) * 25;
return(t >> 2);
}
void main()
{
unsigned int tmp;
unsigned char counter = 20;
while(1)
{
// Control the measurement frequency using a counter
if (counter-- == 0)
{
tmp = readTemperature();
counter = 20;
}
P2 = 0xff;
P0 = disp[tmp % 10];
P2 = 0xfb;
delay_18B20(1000);
P2 = 0xff;
P0 = disp[tmp / 10 % 10];
P2 = 0xf7;
delay_18B20(1000);
P2 = 0xff;
P0 = disp_dot[tmp / 100 % 10];
P2 = 0xef;
delay_18B20(1000);
P2 = 0xff;
P0 = disp[tmp / 1000 % 10];
P2 = 0xdf;
delay_18B20(1000);
}
}
HVAC Pressure Gauge,Temperature Gauge,Digital Temperature Gauge
ZHOUSHAN JIAERLING METER CO.,LTD , https://www.zsjrlmeter.com