#include <Arduino.
h>
int pHSense = A0; //Defines pHSense as the analog pin A0 where the pH sensor is connected.
int samples = 10; //The number of samples to be taken from the pH sensor in each reading
cycle. This helps to average out the noise.
float adc_resolution = 1024.0; //This represents the analog-to-digital converter (ADC)
resolution. Arduino's ADC is 10-bit, so it can output values from 0 to 1023 (thus a resolution of
1024).
void setup()
Serial.begin(9600); //Initializes serial communication at 9600 baud rate.
delay(100); //Introduces a small delay of 100 milliseconds to ensure the serial communication
starts properly.
Serial.println("pH Sensor"); //Prints the text "pH Sensor" to the serial monitor to indicate the
program has started.
float ph (float voltage) {
//This function calculates the pH value based on the voltage from the pH sensor.
//The formula used here assumes that the voltage at pH 7 is 2.5V, and the pH scale varies by
approximately 0.18V per pH unit.
return 7 + ((2.5 - voltage) / 0.18); //means that if the voltage is higher than 2.5V, the pH will be
lower than 7 (acidic), and if the voltage is lower, the pH will be higher than 7 (basic).
void loop()
int measurings=0; //This variable stores the sum of the samples taken from the pH sensor.
for (int i = 0; i < samples; i++) //10 sample readings
measurings += analogRead(pHSense);
delay(10);
float voltage = 5 / adc_resolution * measurings/samples;
//measurings / samples calculates the average analog value from the sensor. Multiplying this by
5 / adc_resolution converts the average ADC value to voltage, where 5V is the reference voltage
and 1024 is the maximum ADC resolution.
Serial.print("pH= ");
Serial.println(ph(voltage)); //The calculated voltage is passed to the ph() function to convert it to
a pH value.
delay(3000); //The program waits for 3 seconds (delay(3000);) before taking the next set of
samples.