 # Understanding pH code

Hello guys, I’m a newbie and I’m currently working on a project to build a pH meter. I read other posts about pH meter, but I was not able to understand some parts of the code. The code is working, no problem with that, I tested two buffer solutions (pH=4,0 and pH=7,0) and they retrieved a perfect match in the serial monitor. I just don’t want to use a code without knowing how it works.

Source of the code and more informations on how pH meters work: How to use a PH probe and sensor - Bot Shop

``````float calibration = 0.00;       // change this value to calibrate
const int analogInPin = A0; // pin which the sensor is connected
int sensorValue = 0;          // there's no further reference to this
unsigned long int avgValue;
float b;                            // there's no further reference to this
int buf,temp;             // what's this temp for?
void setup() {
Serial.begin(9600);
}
void loop() {
for(int i=0;i<10;i++)     // get 10 sample value from the sensor for smooth the value
{
delay(30);
}
for(int i=0;i<9;i++)      // sort the analog from small to large(?) How come?
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];               // these equations work as a reset to the values?
buf[i]=buf[j];
buf[j]=temp;
}
}
}
avgValue=0;
for(int i=2;i<8;i++)                                          // take the average value of 6 center sample
avgValue+=buf[i];
float phValue = -5.70 * pHVol + calibration;      // this comes from a linear function
Serial.print("sensor = ");
Serial.println(phValue);
delay(500);
}
``````

Thanks so much for your attention.

(deleted)

Assuming that the questions in the code are the ones that you should have asked in the post , this comment in the code explains why the data must be sorted:

// take the average value of 6 center samples

This is a noise filter approach, related to the median filter.

spycatcher2k:
Which SPECIFIC lines / blocks do you not understand?

Sorry, I made my questions in the comments within the code I posted. I don’t see a reason to declare int sensorValue = 0, if it’s not been used after, and so does float b. I suppose this code is a part of some original code that someone may have cut, am I right?

My doubts remain on these constructions, (what they do?):

``````for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(buf[i]>buf[j])
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
}
}
avgValue=0;
``````

jremington:
Assuming that the questions in the code are the ones that you should have asked in the post , this comment in the code explains why the data must be sorted:
This is a noise filter approach, related to the median filter.

Thanks for your answear jremington, I'll search this subject. And sorry about the incorrect posting.

My doubts remain on these constructions

Simple sort of the data.

If variables are declared in the code but never used, remove those declarations.