Arduino code techniques
Aus www.wiki.ardumower.de
Version vom 13. September 2014, 19:12 Uhr von Alexanderg (Diskussion | Beiträge) (→Low pass filter)
This page shows example code, common code techniques etc. that can be useful for your own programming experiments with the Arduino.
Low pass filter
- Problem: you have multiple ADC measurements (battery, ultrasonic etc.) that can quickly change. What value is the 'smooth value' (low-pass filter)?
- Solution: This code will apply a 'low-pass' filter to your values. A 'weight' constant specifies the cut-off frequency, so how much your values are 'smoothed'. If the weight is higher, the cutt-off frequency is lower (so more is filtered out), however the more slowly the system adapts to the last measurements.
float value = 0.0; float weight = 0.9; // how much your values are 'smoothed'
void loop(){ value = (1.0-weight) * value + weight * analogRead(A0); // low-pass values Serial.println(value); // print value }
Mean filter
- Problem: you have multiple ADC measurements (battery, ultrasonic etc.) that can contain outliers. What value is the 'most seen value'?
- Solution: This code will sort and choose the center value.
- Example measurements: 32,7,7,1,6,8,7,9,23,7,8,9,7
- Sorted: 1,6,7,7,7,7,7,8,8,9,9,23,32
- Returned: 7 (center value)
unsigned int ADCmedian(int pin, int count) { int values[count], last; uint8_t j, i = 0; values[0] = 0; while (i < count) { last = analogRead(pin); if (i > 0) { for (j = i; j > 0 && values[j - 1] < last; j--) // Insertion sort loop. values[j] = values[j - 1]; // Shift ping array to correct position for sort insertion. } else j = 0; // First ping is starting point for sort. values[j] = last; // Add last ping to array in sorted position. i++; // Move to next ping. if (i < count) delay(1); } return (values[count/2]); // Return the median. }