1

Adding another flow sensor to sketch

I have a water flow sketch I use for my freshwater consumption. I would like to adapt it to use for diesel fuel consumption. The difference is with a diesel motor the fuel pump sucks more fuel than it burns from the fuel tank and simply returns the excess to the fuel tank. ie there are 2 hoses from the fuel tank, one to the motor, and one back to the tank. The difference between what went to the motor and what went back to the tank is how much fuel the motor burned.

So my plan is to have 2 flow sensors (Yf-s201), and subtract the out put of one from the other and print the difference.

I have a sketch that already works to print L/m and total L. For one sensor on PIN D2. I have defined another sensor on PIN D3.

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

byte sensorInterrupt2 = 1;  //11 = digital pin 3
byte sensorPin2       = 3;

My first road block is to print them individually. as is they both just add to a single total.

I have tried to just copy bits of code and add a "2" but I really don't have any programing knowledge so I am just stabbing in the dark. I don't understand how to call upon the value the code has calculated.

This is the whole sketch:

/*
Liquid flow rate sensor -DIYhacking.com Arvind Sanjeev

Measure the liquid/water flow rate using this code. 
Connect Vcc and Gnd of sensor to arduino, and the 
signal line to arduino digital pin 2.
 
 */
// include the library code:
#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4); 


byte statusLed    = 13;

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorPin       = 2;

byte sensorInterrupt2 = 1;  // 1 = digital pin 3
byte sensorPin2       = 3;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 7.55;  //biger more / min

volatile byte pulseCount;  

float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

unsigned long oldTime;

void setup()
{
  
  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);
lcd.init();
lcd.backlight();
     lcd.begin(16, 2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("S.V. SAVANNAH");
   lcd.setCursor(0,1);
   lcd.print("DAY TANK FLOW METER");
   
  // Set up the status LED line as an output
  pinMode(statusLed, OUTPUT);
  digitalWrite(statusLed, HIGH);  // We have an active-low LED attached
  
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;
  oldTime           = 0;

  // The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
  // Configured to trigger on a FALLING state change (transition from HIGH
  // state to LOW state)
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

/**
 * Main program loop
 */
void loop()
{
   
   if((millis() - oldTime) > 1000)    // Only process counters once per second
  { 
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);
        
    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;
    
    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();
    
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;
    
    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;
      
    unsigned int frac;
    
    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print("L/min");
    Serial.print("\t");       // Print tab space

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");        
    Serial.print(totalMilliLitres);
    Serial.println("mL"); 
    Serial.print("\t");       // Print tab space
  Serial.print(totalMilliLitres/1000);
  Serial.print("L");



   
      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print(int(flowRate));  // Print the integer part of the variable
      lcd.print("L/min ");

    // Print the cumulative total of litres flowed since starting
    lcd.setCursor(2,1);
    lcd.print("Total ");        
  lcd.print(totalMilliLitres/1000.00);
  lcd.print("L");

    // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;
    
    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}'''

 

2 Answers 2

1

Your code currently does not use the second flow sensor. I guess you have problems in designing the code, so I try to walk you trough.

First let's look at the prerequisites, that are needed for the two flow sensors. You already have defined the pins of the flow sensors. You are also defining the number of the corresponding interrupts. In fact you don't have to do that. You can easily get the number of the interrupt through the function digitalPinToInterrupt(pin). So we are left with the pin definition. I would suggest using clearer names:

int flow_out_pin = 2;
int flow_in_pin = 3;

flow_out meaning leaving the tank, flow_in coming back into the tank.

Then in setup() we need to initiate the pins. You have this

pinMode(sensorPin, INPUT);
digitalWrite(sensorPin, HIGH);

This can be then made shorter in one line per sensor:

pinMode(flow_out_pin, INPUT_PULLUP);
pinMode(flow_in_pin, INPUT_PULLUP);

Now we attach the interrupts to the pins:

attachInterrupt(digitalPinToInterrupt(flow_out_pin), flowOutPulseCounter, FALLING);
attachInterrupt(digitalPinToInterrupt(flow_in_pin), flowInPulseCounter, FALLING);

I used the mentioned function to get the interrupt number and changed the name of the ISR. Here comes a different principle, than your firstly intended way: I would let the sensors count in their own ISR and own variables and only calculate the difference to display it. For that we need to define our 2 ISRs:

void flowOutPulseCounter()
{
    flowOutPulseCount++;
}
void flowInPulseCounter()
{
    flowInPulseCount++;
}

The count variables of course need to be defined (globally at the top of the sketch):

volatile byte flowOutPulseCount = 0;
volatile byte flowInPulseCount = 0;

Now we have left the code in loop(), which calculates flowrate, fill level and such and displays them. First: When handling interrupt data in the main code, you want to absolutely minimize the time spend with the interrupts deactivated (since in that time you might miss pulses and thus introduce errors). Normally you would just copy the data into local variables, turn on the interrupts again and do the calculation with the local variables. Something like this (inside the millis() if statement):

// Detach interrupts
detachInterrupt(digitalPinToInterrupt(flow_out_pin));
detachInterrupt(digitalPinToInterrupt(flow_in_pin));

// copy pulse count variables
byte local_flow_out_count = flowOutPulseCount;
byte local_flow_in_count  = flowInPulseCount;

// reset pulse counter variables
flowOutPulseCount = 0;
flowInPulseCount = 0;

// Reattach interrupts
attachInterrupt(digitalPinToInterrupt(flow_out_pin), flowOutPulseCounter, FALLING);
attachInterrupt(digitalPinToInterrupt(flow_in_pin), flowInPulseCounter, FALLING);

// Do calculations using above local variables and display the results
...

For the calculations you would then calculate a flow rate and the total flow from each pulse count. With that you can then calculate the total net flow and the fill level.

Note: You might wanna change the variable type for the counters to unsigned int to get a greater margin, before they overflow, since that would mean incorrect results and it doesn't hurt you to use it.

2
  • Thanks for the great response. I have worked through your suggestions, and I have got as far as: void flowOutPulseCounter() { flowOutPulseCount++; } void flowInPulseCounter() { flowInPulseCount++; } But I get "a function-definition is not allowed here before '{' token" error. Which I don't really even remotely understand. Apr 23, 2021 at 1:49
  • That means either you have put these functions into another function, which is wrong, or you have mismatched curly braces in the code above these functions
    – chrisl
    Apr 23, 2021 at 6:31
0

As chrisl already provided a very good answer, I am just adding some notes here to complement it.

The variable pulseCount is only 8-bits. It will overflow if the flow rate gets above 33.7 L/min. If the possibility exists that the actual flow exceeds this rate, then, as pointed out in chrisl's answer, you should use a 16-bit counter. If, on the other hand, you are sure that this value cannot be exceeded, then you can keep an 8-bit counter, and benefit from the fact that accesses to 8-bit values are atomic. This means you do not need to ever disable interrupts:

// In global scope:
byte oldPulseCount;

// Within loop(), once per second:
byte newPulseCount = pulseCount;  // atomic read
byte pulseCountDifference = newPulseCount - oldPulseCount;
oldPulseCount = newPulseCount;  // save current value

then you compute the flow rate from pulseCountDifference. Note that overflows of pulseCount are harmless, as the difference newPulseCount - oldPulseCount wraps modulo 256 to the correct value. Note also that pulseCount is never reset, as doing so could lead to miscounting whenever an interrupt fires after pulseCount is read but before it is reset.

// Note the time this processing pass was executed. Note that because
// we've disabled interrupts the millis() function won't actually be
// incrementing right at this point, but it will still return the value
// it was set to just before interrupts went away.
oldTime = millis();

This comment is wrong. The statement detachInterrupt(sensorInterrupt) disables only an external interrupt. It does not disable interrupts globally, and specifically does not disable the timer interrupt that increments millis(). There is therefore no guarantee that the various calls to millis() will return the same value within one iteration. Instead, millis() should be called only once, and its value remembered:

void loop()
{
    unsigned long now = millis();  // save this value
    if (now - oldTime >= 1000) {
        // ...
        oldTime = now;
    }
}

Note that I use >= for checking the delay: with the > operator the period is at least 1001 ms.

flowMilliLitres = (flowRate / 60) * 1000;

This is incorrect. It should be

flowMilliLitres = (flowRate / 60) * (now - oldTime);

for the same reason that now - oldTime is used in the computation of flowRate. It may be noted that this can be simplified to

flowMilliLitres = (1e3/calibrationFactor/60) * pulseCountDifference;

as the factors now - oldTime cancel out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.