Back to Parent

// Using a push button and a flex sensor at different bend thresholds
// Assigning pins between the two led lights, button switch, and the flex sensor
int ledPin1 = D3; // First LED (Red)
int ledPin2 = D2; // Second LED (Orange)
int buttonPin = D4; // Push button switch
int flexPin = A0;  // Flex sensor

// Thresholds for flex sensor readings
const int mediumBend = 700; // Threshold for medium bend
const int highBend = 1000;   // Threshold for high bend

void setup() {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(buttonPin, INPUT_PULLUP);
    pinMode(flexPin, INPUT);

    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
}

void loop() {
    int flexValue = analogRead(flexPin);

    if (digitalRead(buttonPin) == LOW) {
        // Button is pressed
        if (flexValue >= highBend) {
            // High bend - Blink lights quickly 10 times
            for (int i = 0; i < 10; i++) {
                digitalWrite(ledPin1, HIGH);
                digitalWrite(ledPin2, HIGH);
                delay(50); // Short delay for quick blink
                digitalWrite(ledPin1, LOW);
                digitalWrite(ledPin2, LOW);
                delay(50); 
            }
            delay(1000); // Pause for a second after blinking
        } else if (flexValue >= mediumBend) {
            // Medium bend - Alternate blinking three times
            for (int i = 0; i < 3; i++) {
                digitalWrite(ledPin1, HIGH);
                digitalWrite(ledPin2, LOW);
                delay(500); 
                digitalWrite(ledPin1, LOW);
                digitalWrite(ledPin2, HIGH);
                delay(500); 
            }
            digitalWrite(ledPin2, LOW); // Both LEDs are off after blinking
            delay(1000); // Pause for a second after blinking
        } else {
            // Below medium bend - both LEDs off
            digitalWrite(ledPin1, LOW);
            digitalWrite(ledPin2, LOW);
        }
    } else {
        // Button is not pressed
        if (flexValue >= mediumBend && flexValue < highBend) {
            // Medium bend - only RED LED on
            digitalWrite(ledPin1, HIGH);
            digitalWrite(ledPin2, LOW);
        } else if (flexValue >= highBend) {
            // High bend - both LEDs on
            digitalWrite(ledPin1, HIGH);
            digitalWrite(ledPin2, HIGH);
        } else {
            // Below medium bend - both LEDs off
            digitalWrite(ledPin1, LOW);
            digitalWrite(ledPin2, LOW);
        }
    }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

1