#include "DHT.h"
#define DHTPIN 32
#define DHTTYPE DHT22
#define LDRPIN 33
#define BTNPIN 4
#define BIT_PRINT_SENSOR_DATA ( 1 << 0 )
DHT dht(DHTPIN, DHTTYPE);
static hw_timer_t *readSensorTimer = NULL;
volatile float h, t, lux;
EventGroupHandle_t evt;
static const uint16_t timer_divider = 5;
static const uint32_t clock_freq = 1000000;
uint64_t lastDebounceTime = 0;
static uint8_t debounceDelay = 100;
void IRAM_ATTR readSensors() {
h = dht.readHumidity();
t = dht.readTemperature();
// if (isnan(h) || isnan(t)) {
// Serial.println(F("Failed to read from DHT sensor!"));
// return;
// }
const float GAMMA = 0.7;
const float RL10 = 50;
// int analogValue = analogRead(LDRPIN); // Crashes on hardware interrupt
// float voltage = analogValue / 4095. * 5;
// float resistance = 2000 * voltage / (1 - voltage / 5);
// lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
xEventGroupSetBits(
evt, /* The event group being updated. */
BIT_PRINT_SENSOR_DATA
);/* The bits being set. */
}
void handleButtonPress() {
if ((millis() - lastDebounceTime) > debounceDelay) {
xEventGroupSetBits(
evt, /* The event group being updated. */
BIT_PRINT_SENSOR_DATA
);/* The bits being set. */
lastDebounceTime = millis();
}
}
void printSensorData(void *m) {
while (1) {
EventBits_t uxBits = xEventGroupWaitBits(
evt, /* The event group being tested. */
BIT_PRINT_SENSOR_DATA, /* The bits within the event group to wait for. */
pdTRUE, /* Should be cleared before returning. */
pdFALSE, /* Don't wait for both bits, either bit will do. */
portMAX_DELAY
);
Serial.println("print sensor data");
if ((uxBits & BIT_PRINT_SENSOR_DATA) != 0) {
Serial.printf("Humidity: %.2f\n", h);
Serial.printf("Temperature: %.2f\n", t);
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(BTNPIN, INPUT_PULLUP);
/* Attempt to create the event group. */
evt = xEventGroupCreate();
/* Was the event group created successfully? */
if (evt == NULL) {
/* The event group was not created because there was insufficient
FreeRTOS heap available. */
Serial.println(F("Failed to create event group!"));
}
readSensorTimer = timerBegin(clock_freq);
timerAttachInterrupt(readSensorTimer, &readSensors);
timerAlarm(readSensorTimer, clock_freq * timer_divider, true, 0);
attachInterrupt(digitalPinToInterrupt(BTNPIN), handleButtonPress, FALLING);
TaskHandle_t taskPrintSensorData = NULL;
xTaskCreate(printSensorData, "Print Sensor Data", 4094, NULL, 1, &taskPrintSensorData);
dht.begin();
}
void loop() {
delay(10);
}