This circuit consists of an ESP-8266 microcontroller, a 5V battery, and an Adafruit 24 NeoPixel Ring. The ESP-8266 controls the NeoPixel Ring, and the entire circuit is powered by the 5V battery. The microcontroller is programmed to control a motor and an LED based on the state of a switch.
// Motor control pins
#define IN_A 4 // GPIO4 (D2)
#define IN_B 5 // GPIO5 (D1)
// Switch pin
#define SWITCH_PIN 14 // GPIO14 (D5)
// LED pin
#define LED_PIN 2 // GPIO2 (D4)
// Motor state
bool motorRunning = false;
void setup() {
// Motor pins setup
pinMode(IN_A, OUTPUT);
pinMode(IN_B, OUTPUT);
// Switch pin setup
pinMode(SWITCH_PIN, INPUT_PULLUP); // Use internal pull-up resistor
// LED pin setup
pinMode(LED_PIN, OUTPUT);
// Start with motor and LED off
digitalWrite(IN_A, LOW);
digitalWrite(IN_B, LOW);
digitalWrite(LED_PIN, LOW);
Serial.begin(9600);
Serial.println("Setup Complete. Press the switch to toggle the motor.");
}
void loop() {
// Check if the switch is pressed
if (digitalRead(SWITCH_PIN) == LOW) {
// Debounce delay
delay(50);
if (digitalRead(SWITCH_PIN) == LOW) {
// Toggle motor state
motorRunning = !motorRunning;
if (motorRunning) {
startMotor();
} else {
stopMotor();
}
// Wait for the switch to be released
while (digitalRead(SWITCH_PIN) == LOW);
}
}
}
void startMotor() {
Serial.println("Motor started.");
analogWrite(IN_A, 255); // Full speed forward
digitalWrite(IN_B, LOW);
digitalWrite(LED_PIN, HIGH); // Turn on LED
}
void stopMotor() {
Serial.println("Motor stopped.");
digitalWrite(IN_A, LOW);
digitalWrite(IN_B, LOW);
digitalWrite(LED_PIN, LOW); // Turn off LED
}
This code sets up the ESP-8266 to control a motor and an LED based on the state of a switch. The motor and LED are toggled on and off when the switch is pressed. The code includes debouncing logic to ensure reliable switch operation.