This circuit is designed to control two LEDs using an Arduino Nano microcontroller. The LEDs are turned on for a fixed duration when a pushbutton is pressed. The circuit uses non-blocking timers to manage the LED on-time, which allows the microcontroller to perform other tasks concurrently if necessary.
/*
* This Arduino Sketch controls two LEDs connected to pins D2 and D3. When a pushbutton
* connected to pin D4 is pressed, both LEDs will turn on for 5 seconds. The code uses
* non-blocking timers to manage the LED on-time, allowing the microcontroller to
* perform other tasks if needed.
*/
const int buttonPin = 4; // Pin connected to the pushbutton
const int ledPin1 = 2; // Pin connected to the first LED
const int ledPin2 = 3; // Pin connected to the second LED
bool buttonState = false; // Current state of the button
bool lastButtonState = false; // Previous state of the button
unsigned long ledOnTime = 5000; // LED on duration in milliseconds
unsigned long previousMillis = 0; // Stores the last time the LEDs were turned on
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
void loop() {
unsigned long currentMillis = millis();
buttonState = digitalRead(buttonPin);
// Check if the button is pressed
if (buttonState && !lastButtonState) {
// Turn on the LEDs
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
previousMillis = currentMillis; // Record the time the LEDs were turned on
}
// Check if the LEDs should be turned off
if (currentMillis - previousMillis >= ledOnTime) {
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
lastButtonState = buttonState; // Update the last button state
}
This code is written for the Arduino Nano and is saved as sketch.ino
. It initializes the pushbutton and LEDs, reads the button state, and controls the LEDs based on the button press. The LEDs are turned on for 5 seconds when the button is pressed.