In this tutorial, we’ll use an end switch (also known as a limit switch) with an ESP32 to simulate a crash detection system. The end switch will act as a simple sensor that detects when it’s pressed, indicating a “crash.”
Buy the Parts
- RC Car Wltoys K989 ……………………….… Amazon/ Banggood / Shopee
- ESP32 C6 Super Mini …………………….… Amazon / Banggood / Shopee
- Limit Switch / End Switch ………………… Amazon/ Banggood / Shopee
Disclosure: These are affiliate links. I earn a little comission if you use my links to buy the parts.
Please use them to help me continue building cool projects.
How it Works
The end switch acts as a momentary switch. When the lever or button is pressed, the circuit closes, and the ESP32 detects a LOW signal. When released, the circuit opens, and the ESP32 detects a HIGH signal.
Wiring the End Switch
- Connect the common terminal (COM) of the end switch to a GPIO pin on the ESP32 (e.g.,
GPIO14
). - Connect the normally open (NO) terminal of the switch to GND.
- Add a pull-up resistor (10kΩ) between the GPIO pin and
3.3V
(optional but recommended for stable readings).
Step 1: Write the Code
This code detects when the end switch is pressed (indicating a crash) and prints a message to the Serial Monitor.
// Define the pin for the end switch const int crashSensorPin = 5; void setup() { // Initialize the serial monitor Serial.begin(115200); // Set the crash sensor pin as an input pinMode(crashSensorPin, INPUT_PULLUP); // Use internal pull-up resistor Serial.println("Crash sensor ready. Press the switch to simulate a crash!"); } void loop() { // Read the crash sensor state int sensorState = digitalRead(crashSensorPin); // Detect a crash if (sensorState == LOW) { Serial.println("Crash detected!"); } else { Serial.println("No crash detected."); } delay(500); // Wait 500 ms for better readability }
Step 2: Upload the Code
- Connect your ESP32 to your computer via USB.
- Open the Arduino IDE.
- Select the correct board and port under Tools.
- Upload the code.
Step 3: Test Your Setup
- Open the Serial Monitor (set the baud rate to
115200
). - Press the end switch lever or button to simulate a crash.
- You should see “Crash detected!” in the Serial Monitor.
- Release the switch, and you should see “No crash detected.”
Troubleshooting Tips
Switch not detected:
- Check the wiring and ensure the correct GPIO pin is used in the code.
- Verify the switch’s terminals (COM and NO).
Unstable readings:
- Ensure the pull-up resistor is in place or use the internal pull-up resistor in the code (
INPUT_PULLUP
).