#define LIMIT_SWITCH_PIN 7 // Pin for the push button
#define LED_PIN 13 // Pin for an optional LED
unsigned long buttonPressTime = 0; // Time when the button is pressed
unsigned long depthLevel = 0; // Variable to store the depth level (duration of button press)
bool buttonState = false; // Current button state
bool lastButtonState = false; // Previous button state
void setup() {
pinMode(LIMIT_SWITCH_PIN, INPUT_PULLUP); // Use internal pull-up resistor for the push button
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
Serial.begin(9600); // Start serial monitor
}
void loop() {
// Read the button state
buttonState = digitalRead(LIMIT_SWITCH_PIN) == LOW;
// Check for button press event
if (buttonState && !lastButtonState) {
buttonPressTime = millis(); // Start timing when the button is pressed
}
// If the button is being pressed, calculate the "depth" based on how long it’s held
if (buttonState) {
depthLevel = millis() - buttonPressTime; // Calculate depth based on press duration
depthLevel = constrain(depthLevel, 0, 1000); // Limit depth to a maximum value (e.g., 1 second)
}
// If the button is released, display the depth and control LED brightness
if (!buttonState && lastButtonState) {
Serial.print("Depth level: ");
Serial.println(depthLevel); // Show the "depth" on the Serial Monitor
analogWrite(LED_PIN, map(depthLevel, 0, 1000, 0, 255)); // Adjust LED brightness based on depth
}
// Store the current button state for the next loop
lastButtonState = buttonState;
delay(50); // Small delay for debounce
}