const int buttonPin = 2; // The digital pin for the button
const int analogInPin = 36; // The analog input pin
//const unsigned long holdDuration = 1000; // Hold time in milliseconds (1 second)
const unsigned long holdDuration = 5000; // Hold time in milliseconds (1 second)
int heldValue = 0; // Variable to store the "held" analog value
int buttonState = 0; // Current button state
int lastButtonState = 0; // Previous button state
bool valueHeld = false; // Flag to indicate if a value is currently held
unsigned long holdStartTime = 0; // Time when the value was sampled and held
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Check if the button state has changed (detects a press or release)
if (buttonState != lastButtonState) {
// If the button is pressed (LOW due to INPUT_PULLUP configuration)
if (buttonState == LOW) {
// if (digitalRead(2) == 0) {
// If a value is not currently held, sample and hold the new value
if (!valueHeld) {
heldValue = analogRead(analogInPin); // Sample the analog value
holdStartTime = millis(); // Record the time the value was held
valueHeld = true; // Set the flag to indicate value is held
Serial.print("Sampled and held new value: ");
Serial.println(heldValue);
}
else {
// Optionally, handle button presses while a value is held (e.g., ignore them)
// Serial.print(" else = ");
// Serial.println(250);
}
}
/////////////////
else {
// Optionally, handle button presses while a value is held (e.g., ignore them)
Serial.print(" else = ");
Serial.println(250);
}
///////////////////
// Small delay for debouncing
delay(500);
}
// Check if the held duration has passed
if (valueHeld && (millis() - holdStartTime >= holdDuration)) {
valueHeld = false; // Reset the flag, allowing a new sample
Serial.println("Hold duration ended. Ready for new sample.");
}
Serial.print(" pin = ");
Serial.print(analogRead(analogInPin ) - 20);
Serial.print(" pinn = ");
Serial.println(260);
// Use the 'heldValue' for other parts of your code here, e.g., analogWrite() to an LED or display on screen
// If no value is held, heldValue keeps its last sampled value until a new one is sampled
// Update the last button state for the next iteration
lastButtonState = buttonState;
}