uwezi

20220831_ph_calibration

Aug 31st, 2022 (edited)
1,504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // efter Mikael Björnson, Arduinobubblan, 2022-08-31
  2.  
  3. float slope = 0.0;  // slope variable for the pH adjustment, set to zero at start
  4. float offset;     // offset variable for the pH adjustment
  5.  
  6. int pHpin = 8;
  7.  
  8. // storing the values once for multiple use
  9. const float cal_pH[3] = {4.01, 6.86, 9.18};
  10.  
  11. void setup()
  12. {
  13.   pinMode(pHpin,INPUT);
  14. }
  15.  
  16. void loop()
  17. {
  18.   // if the calibration button is pressed or slope is zero, start calibration function
  19.   if ((slope == 0.0) || (calibration_button_pressed))
  20.   {
  21.     pHcalibration();
  22.   }
  23.  
  24.   //every 2 seconds, poll the sensor
  25.   read_pH();
  26. }
  27.  
  28. float read_pH()
  29. {
  30.   return slope * read_raw() + offset;
  31. }
  32.  
  33. float read_raw()
  34. {
  35.   float avg[10];
  36.  
  37.   for (int i=0; i<10; i++) // take 10 readings from the sensor during 100 ms. Store them in an array.
  38.   {
  39.     avg[i] = analogRead(pHpin);
  40.     delay(10);
  41.   }
  42.  
  43.   for (int i=0; i<9; i++) //sorting the readings from low to high
  44.   {
  45.     for (int j=i+1; j<10; j++)
  46.     {
  47.       if (avg[i] > avg[j])
  48.       {
  49.         float temp = avg[i];
  50.         avg[i]   = avg[j];
  51.         avg[j]   = temp;
  52.       }
  53.     }
  54.   }
  55.  
  56.   float avgVal = 0;
  57.   for (int i=2; i<8; i++) // get the total of the 6 middle values.
  58.   {
  59.     avgVal += avg[i];
  60.   }
  61.  
  62.   return avgVal / 6;  // we don't even need to divide by 6 if we do it the same way during calibration and measurement
  63. }
  64.  
  65. void pHcalibration()
  66. {
  67.   //press button when calibration setup is complete for pH cal_pH[0]
  68.   float cal1 = read_raw();
  69.  
  70.   //press button when calibration setup is complete for pH cal_pH[1]
  71.   float cal2 = read_raw();
  72.  
  73.   //press button when calibration setup is complete for pH cal_pH[2]
  74.   float cal3 = read_raw();
  75.  
  76.   // linear least-square fit
  77.   float sumVal = cal1 + cal2 + cal3;
  78.  
  79.   float sumCal = cal_pH[0] + cal_pH[1] + cal_pH[2];
  80.  
  81.   float sumValSquare = pow(cal1,2) + pow(cal2,2) + pow(cal3,2);
  82.  
  83.   float sumProd      = cal1*cal_pH[0] + cal2*cal_pH[1] + cal3*cal_pH[2];
  84.  
  85.   float slope        = (3*sumProd - sumVal * sumCal) / (3*sumValSquare - pow(sumVal,2));
  86.   float offset       = (sumCal - slope * sumVal) / 3;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment