1

I am working on a project to have a open/close a solenoid at certain ranges (using HC-SR04 ultrasonic sensor).

#include <NewPing.h>2

#define Relay1 7 
#define Relay2 8

NewPing SonarRight(12, 11, 400);

void setup() {
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
}

void loop() {

  unsigned int uS1 = SonarRight.ping();
  delay(50); 

  if (uS1 / US_ROUNDTRIP_CM > 15) 
    digitalWrite(Relay1, HIGH);
    delay(100);
    digitalWrite(Relay1, LOW);
    delay(1000);     

  if (uS1 / US_ROUNDTRIP_CM < 5)
    digitalWrite(Relay2, HIGH);
    delay(100);
    digitalWrite(Relay2, LOW);
    delay(1000);
}

I got the sensor to ping correct and the distances are reading accurately. I have it to where once sensor reads that the object is more than 15cm away, the solenoid opens but it keeps clicking open until the object goes back to the dead zone (5-15cm). Same thing when less than 5cm. Essentially what i am trying to accomplish is to have the solenoid fill up a tank when the water level get low. So when the water drops 10cm (x>15) the solenoid opens and then once the water is replenished (x<5), the solenoid closes.

How do i go about doing this without sending a constant OPEN/CLOSE to the solenoid? Is there a way to make a loop to have it send a the signal only once until it exits that defined range?

Please note that i have not actually used it for its intended purpose im supply moving an object back and forth to simulate water distance.

Thanks

1

You have to add a (global) variable that stores the last send command (to open/close).

When you send a command, you save it in the global variable.

And you only send a command when it is different than the command send the last time, so only CHANGES are sent.

The best way to do this is to make a specific function, e.g. SetSolenoid(bool open);

#define SOLENOID_OPEN  TRUE
#define SOLENOID_CLOSE FALSE

bool _currentSolenoidStatus = false; // Assume closed

In your loop:

...
if  ... condition when solenoid should be be opened
{
    SetSolenoid(SOLENOID_OPEN);
}
...
if  ... condition when solenoid should be be closed
{
   SetSolenoid(SOLENOID_CLOSE);
}

Function to open/close solenoid open (only when changed):

bool SetSolenoid(bool status)
{
    if (_currentSolenoidStatus != status)
    {
        // Send status to solenoid
        _solenoidStatus = status;
    }
}
| improve this answer | |

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.