enjoyneering / HTU21D

This is an Arduino library for HTU21D, Si7021 and SHT21 Digital Humidity & Temperature Sensor
55 stars 15 forks source link

Can not use read functions outside loop [ESP-8266] #4

Closed IMAN4K closed 6 years ago

IMAN4K commented 6 years ago

Hi. I've recently test the library with the HTU21D & SI7021 to read the sensor data in some interval callback like this:

#include <ESP8266WiFi.h>
#include <Wire.h>
#include <HTU21D.h>
#include <Ticker.h>

#define D5 14
#define D6 12
#define D3 0
#define D4 2

static Ticker timer;

static HTU21D htu21d;

static void read() {
    if (!htu21d.batteryStatus()) {
        Serial.printf("HTU21D Battery: Not OK! \n");
    }

    float htu_h = htu21d.readHumidity();
    float htu_t = htu21d.readTemperature();
    Serial.printf("HTU21D(T): %f, HTU21D(RH): %f \n", htu_t, htu_h);
}

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

    WiFi.mode(WIFI_OFF);

    while (!htu21d.begin(D5, D6)) {
        Serial.print('.');
        delay(1000);
    }

    if (htu21d.batteryStatus()) {
        Serial.printf("\n HTU21D Battery: OK\n");
    }

    timer.attach(2.0, &read);
}

void loop() {

}

But inside the timer callback, sensors always report battery status as false and the humidity and temperature as error (255 == HTU21D_ERROR).

The situation for polling is not the same and sensors working properly! :

#include <ESP8266WiFi.h>
#include <Wire.h>
#include <HTU21D.h>

#define INTERVAL 2000
#define D5 14
#define D6 12
#define D3 0
#define D4 2

static HTU21D htu21d;

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

    WiFi.mode(WIFI_OFF);

    while (!htu21d.begin(D5, D6)) {
        Serial.print('.');
        delay(1000);
    }

    if (htu21d.batteryStatus()) {
        Serial.printf("\n HTU21D Battery: OK\n");
    }
}

void loop() {
    float htu_h = htu21d.readHumidity();
    float htu_t = htu21d.readTemperature();
    Serial.printf("HTU21D(T): %f, HTU21D(RH): %f \n", htu_t, htu_h);

    delay(INTERVAL);
}

No idea what's the problem here

Setup:

Regards.

IMAN4K commented 6 years ago

After some debugging this is the error point in reading RH. There should be a problem with Arduino TwoWire interface.

IMAN4K commented 6 years ago

This seems to be related to TwoWire interface. No matter how many instance you create, you can just use one instance at a time to communicate with one I2C device ! More specifically, there are some global pin values which is set to twi_init(...) at every construction here