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();

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

  if (uS1 / US_ROUNDTRIP_CM < 5)
    digitalWrite(Relay2, HIGH);
    digitalWrite(Relay2, LOW);

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.


1 Answer 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);


bool _currentSolenoidStatus = false; // Assume closed

In your loop:

if  ... condition when solenoid should be be opened
if  ... condition when solenoid should be be closed

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

bool SetSolenoid(bool status)
    if (_currentSolenoidStatus != status)
        // Send status to solenoid
        _solenoidStatus = status;

Your Answer

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

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