/*
Forum: https://forum.arduino.cc/t/sample-and-hold/1416316
Wokwi: https://wokwi.com/projects/448611877559685121
*/
constexpr byte buttonPin {2}; // The digital pin for the button
constexpr byte analogInPin {A0}; // The analog input pin
constexpr byte ledPin {3};
constexpr byte noOfSamples {10};
constexpr unsigned long holdDuration {5000}; // Hold time in milliseconds (5 second)
uint16_t sampleValue = 0; // Variable to store the "held" analog value
boolean samplingStarted = false; // Flag to indicate if a value is currently held
boolean samplingDone = false;
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
pinMode(ledPin, OUTPUT);
}
void loop() {
readButton();
if (samplingStarted) {
if (samplingHasBeenDone(noOfSamples)) {
holdStartTime = millis(); // Record the time the value was held
samplingDone = true;
samplingStarted = false;
digitalWrite(ledPin, HIGH);
};
}
// Check if the held duration has passed
if (samplingDone && (millis() - holdStartTime >= holdDuration)) {
samplingDone = false; // Reset the flag, allowing a new sample
sampleValue = 0;
digitalWrite(ledPin, LOW);
}
Serial.println(sampleValue);
}
void readButton() {
if (samplingDone) {
return;
}
samplingStarted = !digitalRead(buttonPin);
}
boolean samplingHasBeenDone(int times) {
unsigned long sum = 0;
if (times < 1) {
return false;
}
Serial.println("Start Sampling");
for (int i = 0; i < times; i++) {
sum += analogRead(analogInPin);
}
sampleValue = sum / times;
return true;
}