proteus DHT11温湿度传感实验 仿真 不调用DHT库

一、proteus仿真

  1. 绘制原理图

用到的元器件有:arduino芯片,DHT11,GROVE-UART,VIRTUAL-TERMINSL

proteus DHT11温湿度传感实验 仿真 不调用DHT库_第1张图片
  1. 代码

代码中并没有调用DHT库

int DHT11_PIN = 2;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int humidity = 0;
  int temperature = 0;

  // 发送启动信号并等待响应
  pinMode(DHT11_PIN, OUTPUT);
  digitalWrite(DHT11_PIN, LOW);
  delay(18);
  digitalWrite(DHT11_PIN, HIGH);
  delayMicroseconds(40);
  pinMode(DHT11_PIN, INPUT_PULLUP);

  // 读取传感器响应信号
  unsigned long timeout = micros() + 100000;  // 100 ms
  while (digitalRead(DHT11_PIN) == LOW && micros() < timeout);
  if (micros() >= timeout) return;
  timeout = micros() + 100000;
  while (digitalRead(DHT11_PIN) == HIGH && micros() < timeout);
  if (micros() >= timeout) return;

  // 读取数据
  for (int i = 0; i < 40; i++) {
    timeout = micros() + 100000;
    while (digitalRead(DHT11_PIN) == LOW && micros() < timeout);
    if (micros() >= timeout) return;
    unsigned long t = micros();
    timeout = t + 100000;
    while (digitalRead(DHT11_PIN) == HIGH && micros() < timeout);
    if (micros() >= timeout) return;
    if (micros() - t > 40) {
      if (i < 16) humidity |= (1 << (15 - i));
      else if (i < 32) temperature |= (1 << (31 - i));
    }
  }

  // 输出温度和湿度
  Serial.print("Humidity = ");
  Serial.print((float)humidity / 10);
  Serial.print("%, Temperature = ");
  Serial.print((float)temperature / 10);
  Serial.println("C");

  delay(1000);
}

二、仿真

proteus DHT11温湿度传感实验 仿真 不调用DHT库_第2张图片

你可能感兴趣的:(proteus,单片机)