I want to refactor this code
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
flow_frequency++;
}
void setup()
{
pinMode(flowsensor, INPUT);
digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
Serial.begin(9600);
attachInterrupt(0, flow, RISING); // Setup Interrupt
sei(); // Enable interrupts
currentTime = millis();
cloopTime = currentTime;
}
void loop ()
{
currentTime = millis();
// Every second, calculate and print litres/hour
if(currentTime >= (cloopTime + 1000))
{
cloopTime = currentTime; // Updates cloopTime
// Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
flow_frequency = 0; // Reset Counter
Serial.print(l_hour, DEC); // Print litres/hour
Serial.println(" L/hour");
}
}
Originally found here: source
to an Class based solution:
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
class FlowSensor {
volatile int flow_frequency;
unsigned int l_hour;
unsigned char pin;
unsigned long currentTime;
unsigned long cloopTime;
public:
void flow () {
flow_frequency++;
};
void setup() {
pinMode(pin, INPUT);
digitalWrite(pin, HIGH); // Optional Internal Pull-Up
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(pin), flow, RISING); // Setup Interrupt
sei(); // Enable interrupts
currentTime = millis();
cloopTime = currentTime;
}
void loop() {
currentTime = millis();
// Every second, calculate and print litres/hour
if(currentTime >= (cloopTime + 1000))
{
cloopTime = currentTime; // Updates cloopTime
// Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
flow_frequency = 0; // Reset Counter
Serial.print(l_hour, DEC); // Print litres/hour
Serial.println(" L/hour");
}
}
FlowSensor() {
setup();
};
};
FlowSensor flowsensor_intake;
void setup()
{
flowsensor_intake = FlowSensor();
}
void loop ()
{
flowsensor_intake.loop();
}
But i get the following error in the Arduino IDE:
/tmp/087639235/water_flow/water_flow.ino: In static member function 'static void FlowSensor::flow()':
/tmp/087639235/water_flow/water_flow.ino:17:19: error: cannot call member function 'void FlowSensor::update_flow()' without object
update_flow()
^
exit status 1
I understand that flow is not a static function and that i cannot make it static because it is midifying a non static member.
But i cannot think of an alternate solution to this Problem. My goal is to monitor multiple flow sensors by creating an object in the setup()
function, and updating them with every loop()
call.