{
"name": "ESP32 MPU6050 Servo LED",
"boards": [
{
"id": "esp32devkit",
"type": "esp32",
"label": "ESP32 DevKit",
"pins": 38
}
],
"parts": [
{
"type": "esp32devkit",
"id": "board"
},
{
"type": "mpu6050",
"id": "mpu",
"x": 80,
"y": 80,
"connections": [
["board", "3.3V"],
["board", "GND"],
["board", "GPIO21", "SDA"],
["board", "GPIO22", "SCL"]
]
},
{
"type": "led",
"id": "led",
"x": 140,
"y": 130,
"connections": [
["board", "GPIO2"],
["board", "GND"]
]
},
{
"type": "sg90",
"id": "servo",
"x": 140,
"y": 180,
"connections": [
["board", "GPIO4"],
["board", "3.3V"],
["board", "GND"]
]
}
],
"code": "#include <Wire.h>\n#include <Adafruit_MPU6050.h>\n#include <Adafruit_Sensor.h>\n#include <ESP32Servo.h>\n\nAdafruit_MPU6050 mpu;\nServo myServo;\n\nconst int ledPin = 2;\nconst int servoPin = 4;\nconst float motionThreshold = 1.5;\n\nfloat lastAccelX = 0;\nfloat lastAccelY = 0;\nfloat lastAccelZ = 0;\n\nvoid setup() {\n Serial.begin(115200);\n while (!Serial) delay(10);\n\n Wire.begin(21, 22);\n\n pinMode(ledPin, OUTPUT);\n digitalWrite(ledPin, LOW);\n\n myServo.setPeriodHertz(50);\n myServo.attach(servoPin, 500, 2400);\n myServo.write(0);\n\n if (!mpu.begin()) {\n Serial.println(\"無法找到 MPU6050 感測器!\");\n while (1) delay(10);\n }\n Serial.println(\"MPU6050 初始化成功!\");\n\n mpu.setAccelerometerRange(MPU6050_RANGE_8_G);\n mpu.setGyroRange(MPU6050_RANGE_500_DEG);\n mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);\n}\n\nvoid loop() {\n sensors_event_t a, g, temp;\n mpu.getEvent(&a, &g, &temp);\n\n float deltaX = abs(a.acceleration.x - lastAccelX);\n float deltaY = abs(a.acceleration.y - lastAccelY);\n float deltaZ = abs(a.acceleration.z - lastAccelZ);\n\n if (deltaX > motionThreshold || deltaY > motionThreshold || deltaZ > motionThreshold) {\n digitalWrite(ledPin, HIGH);\n myServo.write(90);\n delay(500);\n myServo.write(0);\n } else {\n digitalWrite(ledPin, LOW);\n }\n\n lastAccelX = a.acceleration.x;\n lastAccelY = a.acceleration.y;\n lastAccelZ = a.acceleration.z;\n\n Serial.print(\"加速度 (m/s^2): X=\");\n Serial.print(a.acceleration.x);\n Serial.print(\" Y=\");\n Serial.print(a.acceleration.y);\n Serial.print(\" Z=\");\n Serial.println(a.acceleration.z);\n\n delay(200);\n}\n"
}