Activating Solenoids at Random Intervals

Hello- I just got my Arduino yesterday, and just joined the forums, so I really am not sure what I am doing. I am using it for an art piece I am working on, and will do my best to explain what I am trying to do.

I am trying to activate each of 5 solenoids at random intervals (less than 15 seconds). Each needs to only be activated for 500 ms.

I have everything wired up and running with the basic "Blink" code, but I can't figure out how to make them stay deactivated for random amounts of time. I just need someone to guide me in the right direction or link me to any helpful sources. I have looked, but maybe not in the right places.

I have everything wired up and running with the basic "Blink" code

Have a look at the slightly more advanced "blink without delay"

AWOL:
Have a look at the slightly more advanced "blink without delay"

You might also want to look at Robin2's demonstration code for several thing at the same time.

something like this:

struct RelayControl{
  bool state = false;
  byte pin;
  unsigned long duration = 500;  // fixed on time
  unsigned long onTime;
  unsigned long offDuration;
  void begin(byte relayPin);
  void process();
};

void RelayControl::begin(byte relayPin)
{
  pin = relayPin;
  pinMode(pin, OUTPUT);
  onTime = millis();
  offDuration = random(500,15000);  // random off interval between 500 and 15000 milliseconds
}

void RelayControl::process()
{
  if (millis() - onTime < duration)
  {
    if (!state)
    {
      digitalWrite(pin, HIGH);
      Serial.print("relay ");
      Serial.print(pin);
      Serial.println(" ON");
      state = true;
    } 
  }
  else if (millis() - onTime < duration + offDuration)
  {
    if (state)
    {
      state = false;
      digitalWrite(pin, LOW);
      Serial.print("relay ");
      Serial.print(pin);
      Serial.println(" OFF");
    }
  }
  else
  {
    offDuration = random(500, 15000);
    onTime = millis();
  }
}

/////////////////////// Main Program /////////////////////

RelayControl relay1, relay2;

void setup() 
{
  Serial.begin(9600);
  relay1.begin(4);
  relay2.begin(5);
}

void loop() 
{
  relay1.process();
  relay2.process();
}
1 Like