const int ledPin = 7; // Pin for the LED
const int buttonPin = 8; // Pin for the button
const int potPin = A0; // Pin for the potentiometer
unsigned long previousMillis = 0; // Stores the last time the LED was updated
long onInterval = 1000; // Interval for LED ON (milliseconds)
long offInterval = 1000; // Interval for LED OFF (milliseconds)
bool timerEnabled = false; // Boolean to control timer on/off state
int buttonState = 0; // Current state of the button
bool ledState = false; // Current state of the LED (on/off)
// Reporting variables
unsigned long totalOnTimeSeconds = 0; // Total time the LED was ON (in seconds)
unsigned long totalOfTimeSeconds = 0; // Total time the LED was ON (in seconds)
int totalOnCount = 0; // Total number of ON events
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Button with internal pull-up resistor
Serial.begin(9600); // Initialize serial communication for debugging (optional)
}
void loop() {
// Read the button state (LOW when pressed due to pull-up)
buttonState = digitalRead(buttonPin);
// Toggle the timer state if the button is pressed
if (buttonState == LOW) {
timerEnabled = !timerEnabled; // Toggle the timer state
delay(200); // Simple debounce mechanism
Serial.print("Timer state: ");
Serial.println(timerEnabled ? "Enabled ------------" : "Disabled ------------");
// If timer is disabled, report totals
if (!timerEnabled) {
Serial.print("Total ON Count: ");
Serial.println(totalOnCount);
Serial.print("Total ON Time (seconds): ");
Serial.println(totalOnTimeSeconds/1000);
Serial.print("Total OF Time (seconds): ");
Serial.println(totalOfTimeSeconds/1000);
Serial.print("Total ON + OF (seconds): ");
Serial.println((totalOnTimeSeconds+totalOfTimeSeconds)/1000);
}
}
// Read the potentiometer value and map it to on and off intervals
int potValue = analogRead(potPin);
onInterval = map(potValue, 0, 1023, 1000, 5000); // Map to a range for ON time
offInterval = 2000; // Fixed OFF time (you can also map this if needed)
// Only run the timer if it's enabled
if (timerEnabled) {
unsigned long currentMillis = millis();
// Check the LED state and manage timing
if (ledState) {
// If the LED is ON, check the onInterval
if (currentMillis - previousMillis >= onInterval) {
// Turn the LED OFF
digitalWrite(ledPin, LOW);
ledState = false; // Update the LED state
previousMillis = currentMillis; // Reset the timer
totalOnCount++; // Increment the ON event counter
totalOnTimeSeconds += onInterval; // 1000; // Add to the total ON time in seconds
totalOfTimeSeconds += offInterval;
Serial.print("LED OFF, current OFF interval: ");
Serial.println(offInterval);
}
} else {
// If the LED is OFF, check the offInterval
if (currentMillis - previousMillis >= offInterval) {
// Turn the LED ON
digitalWrite(ledPin, HIGH);
ledState = true; // Update the LED state
previousMillis = currentMillis; // Reset the timer
Serial.print("LED ON, current ON interval: ");
Serial.println(onInterval);
}
}
}
}
Restart