Skip to content

Instantly share code, notes, and snippets.

@timothyklim
Last active June 3, 2018 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timothyklim/8e77129da7f8852c47bd13c8f398eb12 to your computer and use it in GitHub Desktop.
Save timothyklim/8e77129da7f8852c47bd13c8f398eb12 to your computer and use it in GitHub Desktop.
Arduino pH sensor
double ph1 = 4.01;
double ph2 = 6.86;
double r1 = 2.925; // pH 1 voltage
double r2 = 2.314; // pH 2 voltage
double delta = (ph2 - ph1) / (r2 - r1);
double calibration = ph1 - delta * r1;
const int PoPin = A0;
#define VMax 4.99
#define PinSteps 1023
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth 40
int pHArray[ArrayLenth];
int pHArrayIndex = 0;
void setup() {
Serial.begin(115200);
Serial.print("delta: ");
Serial.println(delta);
Serial.print("calibration: ");
Serial.println(calibration);
Serial.println();
}
void loop() {
static unsigned long samplingTime = millis();
static unsigned long printTime = millis();
static double pHValue, pHVol;
if (millis() - samplingTime > samplingInterval)
{
pHArray[pHArrayIndex++] = analogRead(PoPin);
if (pHArrayIndex == ArrayLenth) pHArrayIndex = 0;
pHVol = avergearray(pHArray, ArrayLenth) * VMax / PinSteps;
pHValue = delta * pHVol + calibration;
samplingTime = millis();
}
if (millis() - printTime > printInterval)
{
Serial.print("Voltage: ");
Serial.print(pHVol, 3);
Serial.print(", pH value: ");
Serial.println(pHValue, 2);
printTime = millis();
}
}
double avergearray(int* arr, int number) {
int i;
int max, min;
double avg;
long amount = 0;
if (number <= 0) {
Serial.println("Error number for the array to avraging!/n");
return 0;
}
if (number < 5) { //less than 5, calculated directly statistics
for (i = 0; i < number; i++) {
amount += arr[i];
}
avg = amount / number;
return avg;
} else {
if (arr[0] < arr[1]) {
min = arr[0]; max = arr[1];
}
else {
min = arr[1]; max = arr[0];
}
for (i = 2; i < number; i++) {
if (arr[i] < min) {
amount += min; //arr<min
min = arr[i];
} else {
if (arr[i] > max) {
amount += max; //arr>max
max = arr[i];
} else {
amount += arr[i]; //min<=arr<=max
}
}//if
}//for
avg = (double)amount / (number - 2);
}//if
return avg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment