momentary switch for a solenoid

First post, first day with Arduino! :slight_smile:

With a project in mind and a few videos under my belt, I've made it here with my first button question. I'd like to edit this code so the button I press switches the circuit on momentarily, instead of staying on or off. This button will signal a solenoid to trigger that's coming from a relay and I don't want to burn out this solenoid with constant voltage (from a single button press).

Thanks for your help!

int pbuttonPin = 12;// connect output to push button
int relayPin = 13;// Connected to relay (LED)

int val = 0; // push value from pin 12
int lightON = 0;//light status
int pushed = 0;//push status


void setup() {
  Serial.begin(9600);
  pinMode(pbuttonPin, INPUT_PULLUP); 
  pinMode(relayPin, OUTPUT);

}

void loop() {
  val = digitalRead(pbuttonPin);// read the push button value

  if(val == HIGH && lightON == LOW){

    pushed = 1-pushed;
    delay(100);
  }    

  lightON = val;

      if(pushed == HIGH){
        Serial.println("Light ON");
        digitalWrite(relayPin, LOW); 
       
      }else{
        Serial.println("Light OFF");
        digitalWrite(relayPin, HIGH);
   
      }     


  delay(100);
}

Having some familiarity with, and a grasp of, the concepts demo'ed in the first five sketches in: IDE/file/examples/digital will prove quite useful.

Basically, set up a timer which is reset when your (input pullup-connected) button is pressed (ie. connected to circuit ground) and runs when the button is not pressed. If the timer is enabled to run and has not yet reached its preset value, drive the solenoid.

so the button I press switches the circuit on momentarily

For what definition of "momentarily"? 5 seconds? 0.005 nanoseconds? 10 minutes?

int pbuttonPin = 12;// connect output to push button
int relayPin = 13;// Connected to relay (LED)

void setup() {
  Serial.begin(9600);
  pinMode(pbuttonPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);

}

void loop() 
{
  if (digitalRead(pbuttonPin))
  {
    Serial.println("Light ON");
    digitalWrite(relayPin, LOW);
  }
  else
  {
    Serial.println("Light OFF");
    digitalWrite(relayPin, HIGH);
  }
}

On for the moment the button is pressed.

evanmars:
On for the moment the button is pressed.

On for the entire time the switch is pressed would be more accurate. Given that moment is still undefined.

Here is a simple solution for beginners.

int pbuttonPin = 12;// connect output to push button
int relayPin = 13;// Connected to relay (LED)

void setup() {
  Serial.begin(9600);
  pinMode(pbuttonPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
}

void loop() {
  int val = digitalRead(pbuttonPin);// read the push button value

  if (val == LOW) {
    Serial.println("Light ON");
    digitalWrite(relayPin, LOW);
    delay(1000); //select here how long you want the relay stay on
  }
   else {
    Serial.println("Light OFF");
    digitalWrite(relayPin, HIGH);
    delay(100);
  }
}