Help on getting solenoid to only open during specific intervals

Hi everyone,

So I created this code which basically opens a solenoid valve which delivers water to some animals each time an IR beam is broken (which would happen each time the mouse in this case goes to lick for water). Now instead of having water be delivered, in other words the solenoid opening at any point in time I want it to only be able to open during specific periods of time for 30s. So for example, 2 min after the start for only 30 sec, then 4 minutes after the start for another 30s and so on. So I would have a list of time points during the start where I would want the IR beam break to deliver water. I am having a lot of doubts about how to create this. I left the code below and would greatly appreciate it if you have any ideas. Thank you in advance!


# define IRPIN 20
# define SENSORPIN 4
# define RELAY_ENABLE 3
//# define SENSORPOWER 5

int sensorState = 0, lastState=0;         // variable for reading the pushbutton status
 
void setup() {
  // put your setup code here, to run once:
  //IRPIN 20
  pinMode(IRPIN,OUTPUT);
  //SENSORPIN 4
  pinMode(SENSORPIN,INPUT);
  //pin for solenoid
  pinMode(RELAY_ENABLE, OUTPUT);

  digitalWrite(SENSORPIN,HIGH);
  //igitalWrite(SENSORPOWER,HIGH);
  digitalWrite(IRPIN, HIGH);
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
 
  sensorState = digitalRead(SENSORPIN);
 
// check if the sensor beam is broken
// if it is, the sensorState is LOW:
  if (sensorState == HIGH) {
//
   Serial.println("unbroken");
  // Serial.println("relay ON"); // if IR is broken write broken and relay on which means water delivered
   
   digitalWrite(RELAY_ENABLE, HIGH); //turn to low the solenoid which opens it
  
   
  }
  else {
// turn LED off:
   
    Serial.println("broken"); //if its unbroken write unbroken
    digitalWrite(RELAY_ENABLE, LOW);
    delay (20);
    digitalWrite(RELAY_ENABLE, HIGH);
    delay(1000);
  }
 lastState = sensorState;

}

please use code tags

Please follow the advice on posting code given in Read this before posting a programming question

In particular note the advice to Auto format code in the IDE and to use code tags when posting code here as it prevents some combinations of characters in code being interpreted as HTML commands such as italics, bold or a smiley character, all of which render the code useless

I am not sure what do you mean, but I would count minutes or seconds. Code would be something like if (time > 30s && time<120s && IR) then open solenoid
and so on.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.