/*
Wokwi | questions
Hi! Can't find what's wrong here, need help.
rs October 10, 2025— 11:09 AM
Project Link: https://wokwi.com/projects/444164113858721793?gh=1
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define OLED_RESET -1
const int LDR_PIN = A0;
const int PIR_PIN = 2;
const int ECHO_PIN = 3;
const int TRIG_PIN = 4;
const int LUZ_UMBRAL_BAJO = 100;
const int LUZ_UMBRAL_ALTO = 900;
const int DISTANCIA_UMBRAL = 20;
const unsigned long DEBOUNCE_DELAY_PIR = 50;
const float MOVIMIENTO_UMBRAL = 1.5;
float prevAccX = 0, prevAccY = 0, prevAccZ = 0;
unsigned long lastDebounceTimePIR = 0;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Adafruit_MPU6050 mpu;
void setup() {
Serial.begin(115200);
display.setRotation(2); // flips screen vertically
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 falló"));
for (;;);
}
display.display();
delay(2000);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Iniciando...");
display.display();
delay(1000);
if (!mpu.begin()) {
Serial.println("Fallo al encontrar el MPU6050");
while (1) {
delay(10);
}
}
Serial.println("MPU6050 encontrado!");
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
pinMode(PIR_PIN, INPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
prevAccX = a.acceleration.x;
prevAccY = a.acceleration.y;
prevAccZ = a.acceleration.z;
}
void loop() {
//Serial.println("Got here!");
display.clearDisplay();
display.setCursor(0, 0);
display.print("Monitoreando...");
display.display();
sensors_event_t a, g, temp;
mpu.getEvent (&a, &g, &temp);
float accX = a.acceleration.x;
float accY = a.acceleration.y;
float accZ = a.acceleration.z;
float deltaAcc = abs(accX - prevAccX) + abs(accY - prevAccY) + abs(accZ - prevAccZ);
if (deltaAcc > MOVIMIENTO_UMBRAL) {
display.print("ALERTA: Movimiento Brusco!");
display.display();
}
}