Back to Parent

int sensorPin = A0;
int sensorReading = 0;
int ledPin = D1;
int ledBrightness = 0;
int switchPin = D5;

unsigned long bendStartTime = 0;
bool isBending = false;
bool ledOn = false;
unsigned long ledOnTime = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
  int buttonState = digitalRead(switchPin);

  if (buttonState == LOW) {  // If the switch is on (LOW when using INPUT_PULLUP and switch is pressed)
    sensorReading = analogRead(sensorPin);

    if (sensorReading < 3800) {
      if (!isBending) {
        isBending = true;
        bendStartTime = millis();
      }
      if (millis() - bendStartTime > 1000 && !ledOn) {
        ledBrightness = 255;  // Turn the LED on full brightness
        analogWrite(ledPin, ledBrightness);
        ledOn = true;
        ledOnTime = millis();
      }
    } else {
      isBending = false;
      bendStartTime = 0;
    }

    if (ledOn && (millis() - ledOnTime > 1000)) {
      ledBrightness = 0;  // Turn the LED off
      analogWrite(ledPin, ledBrightness);
      ledOn = false;
    }
  } else {
    // Turn the LED off if the switch is off
    if (ledOn) {
      ledBrightness = 0; 
      analogWrite(ledPin, ledBrightness);
      ledOn = false;
    }
    isBending = false;  // Reset bending state
  }

  delay(100);  // Small delay to stabilize readings
}
Click to Expand

Content Rating

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

0