通过Proteus软件仿真51单片机温湿度传感器测温实验,并在OLED中显示,保留小数点后三位
时间: 2023-08-15 09:07:07 浏览: 155
好的,我理解了你的问题。为了在Proteus中仿真51单片机温湿度传感器测温实验,并在OLED中显示保留小数点后三位的温度值,我们需要进行以下步骤:
1. 选择合适的51单片机模块和温湿度传感器模块,并将它们连接起来。常见的温湿度传感器模块有DHT11、DHT22、AM2302等,这里我们以DHT11为例进行说明。
2. 创建一个新的Proteus工程,并将选好的51单片机模块和DHT11传感器模块添加到工程中。然后,将它们的引脚连接起来,具体参考单片机和传感器模块的datasheet。
3. 在51单片机中编写程序,读取DHT11传感器的温湿度数据,并将温度值保留小数点后三位后显示在OLED屏幕上。以下是一个简单的程序示例:
```C
#include <reg51.h>
#include <dht11.h>
#include <i2c.h>
#define OLED_ADDR 0x78
void delay(unsigned int t)
{
unsigned int i, j;
for (i = t; i > 0; i--)
for (j = 110; j > 0; j--);
}
void start_i2c()
{
SDA = 1;
delay(1);
SCL = 1;
delay(1);
SDA = 0;
delay(1);
SCL = 0;
delay(1);
}
void stop_i2c()
{
SDA = 0;
delay(1);
SCL = 1;
delay(1);
SDA = 1;
delay(1);
}
void write_i2c(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
SDA = dat & 0x80;
dat <<= 1;
delay(1);
SCL = 1;
delay(1);
SCL = 0;
delay(1);
}
}
void write_cmd(unsigned char cmd)
{
start_i2c();
write_i2c(OLED_ADDR);
write_i2c(0x00);
write_i2c(cmd);
stop_i2c();
}
void write_dat(unsigned char dat)
{
start_i2c();
write_i2c(OLED_ADDR);
write_i2c(0x40);
write_i2c(dat);
stop_i2c();
}
void init_oled()
{
write_cmd(0xAE);
write_cmd(0x20);
write_cmd(0x10);
write_cmd(0xB0);
write_cmd(0xC8);
write_cmd(0x00);
write_cmd(0x10);
write_cmd(0x40);
write_cmd(0x81);
write_cmd(0xFF);
write_cmd(0xA1);
write_cmd(0xA6);
write_cmd(0xA8);
write_cmd(0x3F);
write_cmd(0xAD);
write_cmd(0x8B);
write_cmd(0xD5);
write_cmd(0x62);
write_cmd(0xD9);
write_cmd(0xF1);
write_cmd(0xDA);
write_cmd(0x12);
write_cmd(0xDB);
write_cmd(0x40);
write_cmd(0x20);
write_cmd(0x02);
write_cmd(0xAF);
}
void display_temp(float temp)
{
int integer = (int)temp;
int decimal = (int)((temp - integer) * 1000);
write_cmd(0x21);
write_cmd(0x00);
write_cmd(0x7F);
write_cmd(0x22);
write_cmd(0x00);
write_cmd(0x3F);
write_dat('T');
write_dat('e');
write_dat('m');
write_dat('p');
write_dat(':');
write_dat(integer / 100 + 0x30);
write_dat(integer / 10 % 10 + 0x30);
write_dat('.');
write_dat(decimal / 100 + 0x30);
write_dat(decimal / 10 % 10 + 0x30);
write_dat(decimal % 10 + 0x30);
write_dat('C');
}
void main()
{
float temperature;
unsigned char chk;
init_i2c();
init_oled();
while (1)
{
chk = dht11_read(1, &temperature, NULL);
if (chk == DHT11_OK)
{
display_temp(temperature);
}
delay(2000);
}
}
```
上述代码使用了dht11库和i2c库,需要先在Keil C51中安装这两个库。程序中首先进行了硬件和库的初始化操作。然后在循环中读取DHT11传感器的温度数据,将温度值保留小数点后三位后显示在OLED屏幕上。其中保留小数点后三位的方法为在display_temp()函数中将温度值分解为整数部分和小数部分,然后分别显示。
希望这个示例程序能够帮助你完成Proteus仿真51单片机温湿度传感器测温实验,并在OLED中显示保留小数点后三位的温度值。
阅读全文