1. /* 2. * flowSensor.h 3. * Will White 11/7/17 4. * 5. * Library providing some basic functions for the Adafruit (plastic) flow sensor 6. * Does not use interrupts, not necessary for SG6 Auto (for which this is written) 7. * CheckFlow function is inspired by code written by Adafruit to test the sensor 8. * Current implementation is for binary readings, ie is there flow or isn't there 9. * Flow volumes are not calculated here, can be done in the future. 10. */ 11. 12. #include 13. 14. #define FLOW_PORT PORTD 15. #define FLOW_PIN PIND 16. #define FLOW_DDR DDRD 17. 18. uint8_t flowpin; 19. uint8_t lastState; 20. uint32_t timeCount; 21. uint32_t pulses; 22. float flowRate; 23. 24. /* 25. * initializes the flow sensor to read a particular pin in port D 26. * default pin is 3 27. */ 28. void flowSensorInit(uint8_t pin); 29. 30. /* 31. * Returns a 1 if water is flowing through the sensor, a 0 if no flow is detected. 32. * reading takes about 100 ms (current implementation is relatively inefficient) 33. */ 34. uint8_t isFlowing(void); 35. 36. /* 37. * helper function, reads the input pin and determines if a pulse has occurred. If it ha s, 38. * the flow rate in hertz is calculated. NOT STANDALONE 39. */ 40. void checkFlow(void); 41. void getReadout(uint8_t *reading); 42. float getFlowrate(void); 1. /* 2. * FlowSensor.c 3. * Will White 11/7/17 4. * Implementation of flowSensor.h 5. */ 6. 7. #include "flowSensor.h" 8. #include 9. #define F_CPU 16000000UL 10. #include 11. #include 12. 13. 14. 15. void flowSensorInit(uint8_t pin) { 16. 17. flowpin = pin; 18. FLOW_DDR &= ~(1 << flowpin); //set as regular input (no pull up so it doesn't sour ce current) 19. FLOW_PORT &= ~(1 << flowpin); // should be 0 already but just to be safe 20. 21. } 22. 23. void checkFlow(void) { 24. 25. uint8_t x; 26. 27. x = (PIND & (1<> flowpin; // equals 0 if pin is low, 1 if high 28. 29. if (x != lastState) { 30. if (x == 1) pulses++; 31. lastState = x; 32. flowRate = 1000.0/timeCount; 33. timeCount = 0; 34. } 35. else 36. timeCount++; 37. } 38. 39. uint8_t isFlowing(void) { 40. 41. //lastState = 0; 42. flowRate = 0; 43. int i; 44. 45. for (i = 0; i < 100; i++) { 46. checkFlow(); 47. _delay_ms(1); 48. } 49. 50. if (flowRate > 0) return 1; 51. else return 0; 52. } 53. 54. void getReadout(uint8_t *reading) { 55. 56. uint8_t x; 57. int i; 58. for (i = 0; i < 500; i++) { 59. reading[i] = (PIND & (1<> flowpin; 60. _delay_ms(1); 61. } 62. } 63. 64. float getFlowrate(void) { 65. 66. uint8_t x, laststate = 0; 67. uint32_t count = 0; 68. int i; 69. for (i = 0; i < 1000; i++) { 70. x = (PIND & (1<> flowpin; 71. if (x != laststate && x == 1) // count the rising edges 72. count++; 73. laststate = x; 74. _delay_ms(1); 75. } 76. 77. // 450 pulses per liter 78. return (1.0/450.0)*count*60*0.264172; // liters per second 79. 80. }