noob needing help writing code for relay

Hey im fairly new to this and i need to write a code that uses a button to switch a relay, open and have it turn a motor on and an led, then when the button is pressed again it switches the relay back to its original position.

Here is an example code showing how to toggle (press on - press off) an output with a momentary switch. The switch is wired to ground and a digital input with the pinMode set to INPUT_PULLUP. The switch must be wired that way for the sketch to work. The sketch uses the state change detection method to sense switch transitions (as opposed to on and off). The example is modified to use an active LOW switch (input LOW when switch pressed).

// this constant won't change:
const int  buttonPin = 8;    // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to
// Variables will change:
boolean buttonState = 0;         // current state of the button
boolean lastButtonState = 0;     // previous state of the button

void setup()
{
   // initialize the button pin as a input with internal pullup enabled
   pinMode(buttonPin, INPUT_PULLUP);
   // initialize the LED as an output:
   pinMode(ledPin, OUTPUT);
   // initialize serial communication:
   Serial.begin(9600);
}

void loop()
{
   // read the pushbutton input pin:
   buttonState = digitalRead(buttonPin);
   // compare the buttonState to its previous state
   if (buttonState != lastButtonState)
   {
       if (buttonState == LOW)
      {
         // if the current state is LOW then the button
         // went from off to on:
         Serial.println("on");
         digitalWrite(ledPin, !digitalRead(ledPin)); // toggle the output
      }
      delay(50);
   }
   // save the current state as the last state,
   //for next time through the loop
   lastButtonState = buttonState;
}

thankyou! i will test this out and see how it functions. it looks like exactly what i was needing!

i need it to include a interrupt in the code so that when the button is pressed it stops the action and turns on a 3 light until the interupt is voided. if that makes any sense

kevindiamond:
i need it to include a interrupt in the code so that when the button is pressed it stops the action and turns on a 3 light until the interupt is voided. if that makes any sense

A couple of things wrong with this.

Humans are very slow so there is no need to use an interrupt to detect a button press. Just check the state of the button in each iteration of loop()

An Interrupt Service Routine (ISR) should never be so long that a human eye could detect an LED that is only turned on during the ISR. 100 microsecs would be a very long time for an ISR.

...R