Skip to content

Instantly share code, notes, and snippets.

@schappim
Created April 23, 2024 22:27
Show Gist options
  • Save schappim/a0b9485c30d25a11accc6ddf54a9414a to your computer and use it in GitHub Desktop.
Save schappim/a0b9485c30d25a11accc6ddf54a9414a to your computer and use it in GitHub Desktop.
#define PH_SENSOR_PIN 0 // pH meter Analog output connected to Arduino Analog Input 0
const int NUM_SAMPLES = 10; // Number of samples to take for smoothing the value
const int NUM_SAMPLES_TO_AVERAGE = 6; // Number of center samples to average
unsigned long int averageValue; // Store the average value of the sensor feedback
float pHValue; // Store the calculated pH value
int sensorReadings[NUM_SAMPLES]; // Array to store sensor readings
int tempValue; // Temporary variable for sorting
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
Serial.println("Ready"); // Test the serial monitor
}
void loop() {
// Get 10 sample values from the sensor to smooth the readings
for (int i = 0; i < NUM_SAMPLES; i++) {
sensorReadings[i] = analogRead(PH_SENSOR_PIN);
delay(10); // Small delay between readings
}
// Sort the sensor readings from smallest to largest
for (int i = 0; i < NUM_SAMPLES - 1; i++) {
for (int j = i + 1; j < NUM_SAMPLES; j++) {
if (sensorReadings[i] > sensorReadings[j]) {
tempValue = sensorReadings[i];
sensorReadings[i] = sensorReadings[j];
sensorReadings[j] = tempValue;
}
}
}
// Calculate the average value of the center samples
averageValue = 0;
for (int i = 2; i < NUM_SAMPLES - 2; i++) {
averageValue += sensorReadings[i];
}
averageValue /= NUM_SAMPLES_TO_AVERAGE;
// Convert the analog value to pH
pHValue = (float)averageValue * 5.0 / 1024; // Convert the analog value to millivolts
pHValue = 3.5 * pHValue; // Convert millivolts to pH value
// Print the pH value to the serial monitor
Serial.print("pH: ");
Serial.println(pHValue, 2); // Print the pH value with 2 decimal places
// Blink the LED
digitalWrite(13, HIGH);
delay(800);
digitalWrite(13, LOW);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment