Created
March 28, 2019 22:26
-
-
Save benfasoli/19e0b17b21bf4c1559c76ab3532247d4 to your computer and use it in GitHub Desktop.
Arduino template for polling analog voltages at given interval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ben Fasoli | |
const int n = 6; | |
const int pins[n] = {A0, A1, A2, A3, A4, A5}; | |
const float slope[n] = {1, 1, 1, 1, 1, 1}; | |
const float intercept[n] = {0, 0, 0, 0, 0, 0}; | |
// Board reference voltage measured on aref pin | |
const float refVoltage = 4.93; // V | |
// Schedule sampling interval | |
const long interval = 1000; // ms | |
// Sets oversampling precision | |
// Without modifying ADC prescaler, the analogRead built-in takes 100-us per | |
// iteration. 64 samples occur over a duration of 6.4-ms for each analog channels | |
// so a single "observation" occurs over a 38.4-ms interval. | |
int numSample = 64; // 13-bit | |
unsigned long prevMillis = 0; // ms | |
void setup() { | |
Serial.begin(9600); | |
} | |
void loop() { | |
// Execute main() every interval ms | |
if (millis() - prevMillis >= interval) { | |
prevMillis = millis(); | |
main(); | |
} | |
} | |
void main() { | |
// Reads analog voltages from all defined pins using oversample(pin) and | |
// linearly rescales the voltage using the user defined slope and intercept | |
for (int i = 0; i < n; i++) { | |
float voltage = oversample(pins[i]); | |
float value = (voltage * slope[i]) + intercept[i]; | |
Serial.print(value); | |
if (i < (n - 1)) { | |
Serial.print(','); | |
} | |
} | |
Serial.println(); | |
} | |
float oversample(int pin) { | |
// ADC oversampling based on AVR121 | |
// https://www.microchip.com/wwwAppNotes/AppNotes.aspx?appnote=en591540 | |
// | |
// Reads analog pin numSample times and returns the average voltage | |
float voltageSum = 0; | |
for (int j = 0; j < numSample; j++) { | |
voltageSum += analogRead(pins[i]); | |
} | |
return (voltageSum / numSample) * (5.0 / refVoltage) / 1023.0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment