0

I'm using arduino with analog pressure sensor, temperature sensor and a relay to control water pump. The simple code I wrote works, but I want better control.

#include <OneWire.h>
#include <DallasTemperature.h>

 const int pinCidlaDS = 2;
 int pinA0 = A0;
 int teplota;
 int rele;
 float tlak = 0;  //ideal 290+-

OneWire oneWireDS(pinCidlaDS);
DallasTemperature senzoryDS(&oneWireDS);

void setup() {
 senzoryDS.begin();
 rele = 3;
 pinMode(3, OUTPUT);
 Serial.begin(9600);
}

void loop() {
 tlak = analogRead(A0);
 teplota = (senzoryDS.getTempCByIndex(0));
  if ((tlak < 285) && (teplota < 30)) {
   digitalWrite(rele, LOW);
   delay(7000);
 }
   else {
   digitalWrite(rele, HIGH);
   delay(500);
 };
 Serial.print("Tlak: ");
 Serial.println(tlak);
 Serial.print("Teplota: ");
 senzoryDS.requestTemperatures();
 Serial.print(senzoryDS.getTempCByIndex(0));
 Serial.println(" stupnu Celsia");
 teplota = (senzoryDS.getTempCByIndex(0));
 delay (200);

}

So now I'm using delay to get away from the treshold value. And I wanted to write a code that would work like:

Pressure is lower than 'x', relay ON. Pressure rises to 'Y', relay OFF until Pressure is lower than 'x'.

What should I use? Could you please give me a example, if there is? Thank you very much! :)

2

Implementing hysteresis turns out to be quite straight-forward:

float pressure = read_pressure();
if (pressure < x)
    turn_relay_on();
else if (pressure >= y)
    turn_relay_off();
  • In addition to this answer you can also use millis(); function instead of delay, take a look at BlinkWithoutDelay example in Arduino IDE. – Hamed Oct 19 at 19:30
  • @newbie, with appropriate hysteresis values you might not need any delay logic at all, using either millis() or delay(). The hysteresis range allows you to have a "dead zone" range where nothing changes. It takes time for the temperature to go from the temp/pressure "on value" to the "off value", so the pump turns on and off less frequently. – Duncan C Oct 20 at 20:29
  • It looks like the OP's application makes its pump on / pump off decisions based on both temperature and pressure. We need to know the values for both that should trigger the pump on, and the values that should trigger the pump to go back off again. – Duncan C Oct 20 at 20:31
  • @DuncanC: Hysteresis on two variables is more complex. My usual approach would be to draw, in the (T, P) plane, three regions: pump on, pump off, and an hysteresis band between them. Then write a predicate on the (T, P) pair for each of pump on and pump off. Cutting out a quarter-plane (T<T1 && P<P1 and T>=T2 || P>=P2) is the simplest case, but I would not trust something with such a sharp corner to be anywhere near optimal for any application. – Edgar Bonet Oct 21 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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