// Define the analog pin where the sensor is connected.
#define SENSOR_PIN A0
// Define the pin where the LED is connected.
#define LED_PIN 13
// Define the threshold value for the sensor output to trigger the LED.
#define THRESHOLD 500
// Variable to store the previous time the LED state was changed.
unsigned long previousMillis = 0;
// Interval at which the LED should blink (500ms).
const long interval = 500;
// Variable to store the current LED state.
int ledState = LOW;
/**
* The setup function is called once at the start of the program.
* It sets the LED pin as an output.
*/
void setup() {
pinMode(LED_PIN, OUTPUT);
}
/**
* The controlLedBlink function controls the blinking of the LED based on the sensor input.
* It reads the sensor value and checks if it is above the threshold.
* If the sensor value is above the threshold, it checks if it's time to change the LED state.
* If it is time, it changes the LED state and sets the LED to the new state.
* If the sensor value is below the threshold, it turns off the LED.
*/
void controlLedBlink() {
int sensorValue = analogRead(SENSOR_PIN); // Read the sensor value.
if (sensorValue >= THRESHOLD) { // Check if the sensor value is above the threshold.
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) { // Check if it's time to change the LED state.
previousMillis = currentMillis; // Save the last time the LED state was changed.
if (ledState == LOW) { // If the LED is off, turn it on. If it's on, turn it off.
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN, ledState); // Set the LED to the new state.
}
} else {
digitalWrite(LED_PIN, LOW); // If the sensor value is below the threshold, turn off the LED.
}
}
/**
* The loop function is called repeatedly after the setup function.
* It calls the controlLedBlink function to control the LED blinking based on the sensor input.
*/
void loop() {
controlLedBlink();
}