Project 11
Touch sensor — cycle LEDs
The code.
// Declare
const int TOUCH_PIN = 10;
const int LED_1 = 6;
const int LED_2 = 7;
const int LED_3 = 8;
// Variables to keep track of the system state
int cycleCounter = 0; // Keeps track of which LED should be on (1, 2, or 3)
int currentTouchState = LOW; // Current reading from the digital pin
int lastTouchState = LOW; // Previous reading from the digital pin
void setup() {
Serial.begin(9600);
pinMode(TOUCH_PIN, INPUT);
pinMode(LED_1, OUTPUT);
pinMode(LED_2, OUTPUT);
pinMode(LED_3, OUTPUT);
// Turn on the first LED immediately at startup
updateCycleLEDs();
}
void loop() {
// Read the current state of the touch sensor
currentTouchState = digitalRead(TOUCH_PIN);
// Check if the sensor just changed from LOW to HIGH (a fresh touch)
if (currentTouchState == HIGH && lastTouchState == LOW) {
// Move to the next LED in the sequence
cycleCounter++;
// If it goes past 3, reset back to 1
if (cycleCounter > 3) {
cycleCounter = 1;
}
// Update the physical LEDs to match the counter
updateCycleLEDs();
// Print to monitor for debugging
Serial.print("Touch detected! Active LED: ");
Serial.println(cycleCounter);
delay(50); // Small software debounce delay to prevent double-triggering
}
// Save the current state as the last state for the next loop run
lastTouchState = currentTouchState;
}
// Helper function to turn off all cycle LEDs and only turn on the active one
void updateCycleLEDs() {
digitalWrite(LED_1, LOW);
digitalWrite(LED_2, LOW);
digitalWrite(LED_3, LOW);
if (cycleCounter == 1) {
digitalWrite(LED_1, HIGH);
}
else if (cycleCounter == 2) {
digitalWrite(LED_2, HIGH);
}
else if (cycleCounter == 3) {
digitalWrite(LED_3, HIGH);
}
}