Hi I'm pretty new to cpp. Could someone review my code and explain any pitfalls or problems? Below is the code and an example to read from a flow meter with a hall sensor. Thanks in advance. Greg
/** example
#include "flow.h"
Flow f(3);
Flow f2(4);
volatile unsigned int counter;
void flow_counter() // ISR
{
// Increment the pulse counter
counter ++;
}
void setup()
{
f.start(); //using default ISR
f2.assign_isr(&flow_counter);
f2.assign_counter(&counter);
f2.start();
}
void loop()
{
Serial.printf("flow rate on 3 = %f \n",f.rate());
Serial.printf("flow total = %dml %f%% of 500ml \n",f.total_ml(),f.percent(500));
Serial.printf("flow rate on 4 = %f \n",f2.rate());
delay(1000);
}
*/
#include <math.h>
#include "Arduino.h"
volatile unsigned int flowPulseCounter;
void flowCounter() // ISR
{
// Increment the pulse counter
flowPulseCounter ++;
}
class Flow{
public:
Flow(uint8_t pin)
{
if(flowPin==254)
flowPin = pin;
}
void assign_isr ( void (*isr)()){ this->flowISR = isr; };
void assign_counter (volatile unsigned int * counter ){ this->counter = counter; };
void assign_pin(uint8_t pin){ flowPin = pin; };
void set_calibration_factor( float factor ) { this->calibrationFactor = factor; };
float get_calibration_factor( ) { return this->calibrationFactor; };
uint8_t retrieve_pin(){ return flowPin; };
void start()
{
detachInterrupt(digitalPinToInterrupt(this->flowPin));
*this->counter = 0; // counter is a pointer so * assigns the value at that address to 0
this->flowRate = 0;
this->flowMillilitres = 0;
this->flowMilliseconds = millis();
pinMode(this->flowPin, INPUT_PULLUP);
this->running = true;
attachInterrupt(digitalPinToInterrupt(this->flowPin), this->flowISR, FALLING);
}
void calculate()
{
if(this->running)
{
this->flowRate = ((1000.0 / (millis() - this->flowMilliseconds)) * ( *this->counter )) / this->calibrationFactor;
this->flowMilliseconds = millis();
// convert to millilitres.
this->flowMillilitres = (this->flowRate / 60) * 1000;
// Add the millilitres to the cumulative total
this->totalMillilitres += this->flowMillilitres;
}
}
void stop()
{
detachInterrupt(digitalPinToInterrupt(flowPin));
this->calculate();
this->running = false;
pinMode(this->flowPin, INPUT_PULLUP);
}
bool is_max( uint32_t millilitres )
{
this->calculate();
return (this->totalMillilitres >= millilitres) ? true : false;
}
float percent( uint32_t millilitres )
{
this->calculate();
return (float)((double) this->totalMillilitres / (double) millilitres) * 100.0;
}
float rate ()
{
this->calculate();
return this->flowRate;
}
uint32_t total_ml()
{
this->calculate();
return this->totalMillilitres;
}
private:
uint8_t flowPin=0;
uint32_t flowMilliseconds = 0;
float flowRate=0;
uint32_t flowMillilitres = 0;
uint32_t totalMillilitres = 0;
float calibrationFactor = 4.5;
bool running = false;
void (*flowISR)() = &flowCounter;
volatile unsigned int * counter = &flowPulseCounter;
};