Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #define SensorPin A0 //pH meter Analog output to Arduino Analog Input 0
  2. #define Offset 0.00 //deviation compensate
  3. #define LED 13
  4. #define samplingInterval 20
  5. #define printInterval 800
  6. #define ArrayLenth 40 //times of collection
  7. int pHArray[ArrayLenth]; //Store the average value of the sensor feedback
  8. int pHArrayIndex=0;
  9. void setup(void)
  10. {
  11. pinMode(LED,OUTPUT);
  12. Serial.begin(9600);
  13. Serial.println("pH meter experiment!"); //Test the serial monitor
  14. }
  15. void loop(void)
  16. {
  17. static unsigned long samplingTime = millis();
  18. static unsigned long printTime = millis();
  19. static float pHValue,voltage;
  20. if(millis()-samplingTime > samplingInterval)
  21. {
  22. pHArray[pHArrayIndex++]=analogRead(SensorPin);
  23. if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
  24. voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
  25. pHValue = 3.5*voltage+Offset;
  26. samplingTime=millis();
  27. }
  28. if(millis() - printTime > printInterval) //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  29. {
  30. Serial.print("Voltage:");
  31. Serial.print(voltage,2);
  32. Serial.print(" pH value: ");
  33. Serial.println(pHValue,2);
  34. digitalWrite(LED,digitalRead(LED)^1);
  35. printTime=millis();
  36. }
  37. }
  38. double avergearray(int* arr, int number){
  39. int i;
  40. int max,min;
  41. double avg;
  42. long amount=0;
  43. if(number<=0){
  44. Serial.println("Error number for the array to avraging!/n");
  45. return 0;
  46. }
  47. if(number<5){ //less than 5, calculated directly statistics
  48. for(i=0;i<number;i++){
  49. amount+=arr[i];
  50. }
  51. avg = amount/number;
  52. return avg;
  53. }else{
  54. if(arr[0]<arr[1]){
  55. min = arr[0];max=arr[1];
  56. }
  57. else{
  58. min=arr[1];max=arr[0];
  59. }
  60. for(i=2;i<number;i++){
  61. if(arr[i]<min){
  62. amount+=min; //arr<min
  63. min=arr[i];
  64. }else {
  65. if(arr[i]>max){
  66. amount+=max; //arr>max
  67. max=arr[i];
  68. }else{
  69. amount+=arr[i]; //min<=arr<=max
  70. }
  71. }//if
  72. }//for
  73. avg = (double)amount/(number-2);
  74. }//if
  75. return avg;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement