winlinvip / SimpleDHT

Simple, Stable and Fast Arduino Temp & Humidity Sensors for DHT11 and DHT22. http://learn.adafruit.com/dht
MIT License
144 stars 61 forks source link

Errors with timerone #30

Closed dawidof closed 5 years ago

dawidof commented 5 years ago

Got such code

// Encoder
#include <ClickEncoder.h>
#include <TimerOne.h>

// DHT
#include <SimpleDHT.h>

char outTemp[50];

int pinDHT11 = 3;
SimpleDHT11 dht11(pinDHT11);

ClickEncoder *encoder;
int16_t last, value;

void timerIsr() {
  encoder->service();
}
int encoderValue;
int encoderPosition;

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

  encoder = new ClickEncoder(A2, A3, 4);
  encoder->setAccelerationEnabled(true);

  Timer1.initialize();
  Timer1.setPeriod(1000);
  Timer1.attachInterrupt(timerIsr); 
  last = -1;
}

void loop() {
  value += encoder->getValue();

  if (value/4 != last) {
    encoderValue = value/4;
    encoderPosition = encoderValue%20;

    last = encoderValue;

    if(encoderPosition <0)
      encoderPosition = -encoderPosition;

    Serial.print("last: ");
    Serial.println((int)last);
    Serial.print("position: ");
    Serial.println((int)encoderPosition);
  }

  printTemp();
  delay(50);
}

void printTemp() {
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    delay(100);
    Serial.print("DHT11 failed: ");
    Serial.println(err); 
  }
  else {
    snprintf(outTemp, 50, "       %dC %d%%", (int)temperature, (int)humidity);
    Serial.println(outTemp);
  }
}

Got such output screen shot 2018-10-28 at 19 17 23

Also it freezes for 5 secs about every 5 secs also. So sec working, another 5 sec freezing

ostaquet commented 5 years ago

In the loop(), you're trying to sample data from the sensor every 50ms. The refresh rate of the DHT11 is not so fast. According to the datasheet, you have to wait at least 2000ms between two sampling.

winlinvip commented 5 years ago

@ostaquet 👍