Skip to content

Instantly share code, notes, and snippets.

@martinabrahams
Created January 6, 2019 05:44
Show Gist options
  • Save martinabrahams/b07d7100bba3ed1bc679d4115695ec05 to your computer and use it in GitHub Desktop.
Save martinabrahams/b07d7100bba3ed1bc679d4115695ec05 to your computer and use it in GitHub Desktop.
Arduino sketch (C) to take x sensors and plot them with smoothing. For home made throttle body balancer.
// number of sensors
const int sensors = 4;
// number of frames to smooth
const int smoothing = 5;
const int minVoltage = 950;
const int maxVoltage = 1050;
// 2d array to store historic data for all sensors
float data[sensors][smoothing];
// contains calibration values for each sensor
float cal[sensors];
void setup() {
// put your setup code here, to run once:
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// sensor 1 calibration
cal[0] = 4.59;
// sensor 2 calibration
cal[1] = 4.617;
// sensor 3 calibration
cal[2] = 4.60;
// sensor 4 calibration
cal[3] = 4.62;
// zero out data to start (i dont know if i need to do this)
for (int i=0;i<sensors;i++)
{
for (int k=0;k<smoothing;k++)
{
data[i][k] = 0;
}
}
}
void loop() {
int frameData[4];
frameData[0] = analogRead(A1);
frameData[1] = analogRead(A2);
frameData[2] = analogRead(A3);
frameData[3] = analogRead(A4);
// pass the raw sensor data for logging
log(frameData);
// print min
Serial.print(minVoltage);
// loop through sensor data
for (int i=0;i<sensors;i++)
{
float avg = smoothSensorVal(i);
Serial.print(" ");
Serial.print(avg);
}
// print max and end line
Serial.print(" ");
Serial.println(maxVoltage);
}
void log(int sensorData[])
{
// loop through sensors
for (int i = 0; i < sensors; i++)
{
// get sensor data and conert to pressure
float voltage = convert(sensorData[i], cal[i]);
// left shift array
for (int k=0;k<smoothing;k++)
{
// if last item in array using current voltage
if (k==(smoothing-1))
{
data[i][k] = voltage;
}
else
{
// use item value from the right
float nextVal = data[i][k+1];
data[i][k] = nextVal;
}
}
}
}
// Convert the analog reading (which goes from 1.3 - 4.7) to a presure (800 - 1160):
float convert(int sensorValue, float cal)
{
return sensorValue * (cal / 3.4);
}
// Apply smoothing to sensor value
float smoothSensorVal(int sensorIdx)
{
float total = 0;
for (int i=0;i<smoothing;i++)
{
float d = data[sensorIdx][i];
total = total + d;
}
return total / smoothing;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment