Arduino Code for T Flip-Flop Circuit
cpp
Copy
const int buttonPin = 2; // Pin for the pushbutton
const int ledPin = 13; // Pin for the LED (built-in LED on most Arduino boards)
boolean ledState = false; // Tracks LED state (false = OFF, true = ON)
int lastButtonState = HIGH; // Tracks previous button state (HIGH = not pressed,
assuming pull-up)
unsigned long lastDebounceTime = 0; // Last time the button state changed
const unsigned long debounceDelay = 50; // Debounce delay in milliseconds
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Button pin with internal pull-up resistor
pinMode(ledPin, OUTPUT); // LED pin as output
digitalWrite(ledPin, ledState); // Set initial LED state
}
void loop() {
int buttonState = digitalRead(buttonPin); // Read current button state
// Check if button state has changed
if (buttonState != lastButtonState) {
lastDebounceTime = millis(); // Record time of state change
}
// Wait for debounce period to ensure stable reading
if ((millis() - lastDebounceTime) > debounceDelay) {
// If button is pressed (LOW due to INPUT_PULLUP)
if (buttonState == LOW && lastButtonState == HIGH) {
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState); // Update LED
}
}
lastButtonState = buttonState; // Update last button state
}