I'm working with ESP32 Dev kit1-Dev-Kit1 and MMA8452qMMA8452Q accelerometer. I want the espESP to read the accelerometer for 10s, then go to sleep for 10s.If If within the sleep period, the accelerometer magnitude reading exceedexceeds the threshold, it will also wake up the espESP.
#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");
}
#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");
}