Skip to content

Instantly share code, notes, and snippets.

@delasign
Created March 30, 2024 14:54
Show Gist options
  • Save delasign/c600597ebac23bce1b22cecc3a2a6ba9 to your computer and use it in GitHub Desktop.
Save delasign/c600597ebac23bce1b22cecc3a2a6ba9 to your computer and use it in GitHub Desktop.
Sample Algorithm for clamping or limiting values.
float prevValue = 0.0; // Previous filtered value
float filteredValue;
float maxChange = 10.0; // Maximum allowed change in value between readings
void loop() {
float rawValue = analogRead(A0); // Read the raw analog input
// Calculate the change in value from the previous reading
float valueChange = abs(rawValue - prevValue);
// If the change is greater than the maximum allowed, clamp the value
if (valueChange > maxChange) {
filteredValue = prevValue + (rawValue - prevValue) / valueChange * maxChange;
} else {
filteredValue = rawValue;
}
prevValue = filteredValue;
// Print the filtered value
Serial.println(filteredValue);
delay(10); // Delay to control the sampling rate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment