c51的温度采集数码管显示
时间: 2023-07-03 17:23:16 浏览: 37
下面是基于C51的温度采集并通过数码管显示的代码示例:
```
#include <reg51.h>
#define DQ P1_0 // DS18B20数据线连接到P1.0
sbit D1 = P2^2; // 数码管第1位连接到P2.2
sbit D2 = P2^3; // 数码管第2位连接到P2.3
sbit D3 = P2^4; // 数码管第3位连接到P2.4
sbit D4 = P2^5; // 数码管第4位连接到P2.5
unsigned char code table[] = { // 数码管显示0~9的编码表
0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90
};
void delay(unsigned int i) // 延时函数
{
while(i--);
}
void init_ds18b20() // 初始化DS18B20传感器
{
DQ = 1; // 先将总线拉高
delay(10);
DQ = 0; // 拉低总线
delay(480); // 延时480us~960us
DQ = 1; // 释放总线
delay(60); // 延时60us~240us
if (!DQ) // 如果DS18B20发现总线上有信号响应
{
delay(480); // 再延时480us~960us
DQ = 1; // 释放总线
}
}
void write_ds18b20(unsigned char dat) // 写入数据到DS18B20传感器
{
unsigned char i;
for(i=0; i<8; i++)
{
DQ = 0; // 拉低总线
DQ = dat & 0x01; // 写入数据
delay(5); // 延时5us~15us
DQ = 1; // 释放总线
dat >>= 1;
}
}
unsigned char read_ds18b20() // 读取数据从DS18B20传感器
{
unsigned char i, dat = 0;
for(i=0; i<8; i++)
{
DQ = 0; // 拉低总线
dat >>= 1;
if (DQ) dat |= 0x80; // 读取数据
delay(5); // 延时5us~15us
DQ = 1; // 释放总线
}
return dat;
}
void main()
{
unsigned char temp_h, temp_l;
unsigned int temp;
while(1)
{
init_ds18b20(); // 初始化DS18B20传感器
write_ds18b20(0xcc); // 跳过ROM操作
write_ds18b20(0x44); // 启动温度转换
init_ds18b20(); // 初始化DS18B20传感器
write_ds18b20(0xcc); // 跳过ROM操作
write_ds18b20(0xbe); // 读取温度值
temp_l = read_ds18b20(); // 读取低位温度值
temp_h = read_ds18b20(); // 读取高位温度值
temp = temp_h;
temp <<= 8;
temp |= temp_l;
temp *= 625;
temp >>= 4;
D1 = table[temp / 1000]; // 显示千位
D2 = table[temp / 100 % 10]; // 显示百位
D3 = table[temp / 10 % 10]; // 显示十位
D4 = table[temp % 10]; // 显示个位
delay(200); // 延时200ms
}
}
```
这段代码中,首先初始化DS18B20传感器,然后启动温度转换,读取温度值,再通过数码管显示温度值。需要注意的是,DS18B20传感器的数据线连接到P1.0,而数码管的四个位分别连接到P2.2~P2.5。