Skip to main content
4 of 4
Corrected capitalisation of products, corrected grammar. Enabled syntax highlighting.

Combining esp_wakeup_timer with external interrupt ext0

I'm working with ESP32-Dev-Kit1 and MMA8452Q accelerometer. I want the ESP to read the accelerometer for 10s, then go to sleep for 10s. If within the sleep period, the accelerometer magnitude reading exceeds the threshold, it will also wake up the ESP.

#include <Wire.h>
#include "SparkFun_MMA8452Q.h"

MMA8452Q accel;

void setup()
{
  Serial.begin(9600);
  Serial.println("MMA8452Q Test Code!");

  accel.init(SCALE_2G, ODR_6);

  // Configure the wake-up source
  esp_sleep_enable_ext0_wakeup(GPIO_NUM_33, 0); // GPIO 33, HIGH logic level
}

void loop()
{
  // Read accelerometer and print values for 10 seconds
  unsigned long startTime = millis();
  unsigned long duration = 10000; // 10 seconds
  while (millis() - startTime < duration) {
    if (accel.available()) {
      accel.read();
      printCalculatedAccels();
    }
  }

  // Sleep for 10 seconds or wake up immediately if magnitude > 1.0
  Serial.println("Going to sleep or waking up if magnitude exceeds 1.0...");
  Serial.flush(); // Ensure all serial data is sent
  float magnitude = sqrt(pow(accel.cx, 2) + pow(accel.cy, 2) + pow(accel.cz, 2));
  if (magnitude > 1.0) {
    Serial.println("Magnitude exceeded 1.0, waking up...");
    esp_sleep_enable_ext0_wakeup(GPIO_NUM_33, 1);
    esp_deep_sleep_start();
    
  } else {
    esp_sleep_enable_timer_wakeup(10 * 1000000); // 10 seconds
    esp_deep_sleep_start();
  }
}

void printCalculatedAccels()
{
  Serial.print(accel.cx, 3);
  Serial.print("\t");
  Serial.print(accel.cy, 3);
  Serial.print("\t");
  Serial.print(accel.cz, 3);
  Serial.println("\t");
}

Lily
  • 11
  • 2