timed relay

const int buttonPin = 2;     
const int ledPin =  12;     
int buttonState = 0;
        
void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}
void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay (8000);
    digitalWrite(ledPin, LOW);
    delay(5000);
  }
}

I have a question.

I want to turn a relay on after lets say 2 minutes stay on for say 5 minutes and then turn off. The way the code is now it keeps looping. the problem I have is, When I write "for(;;){}" the relay stays on forever. The same thing happens when I put the code in the void setup

I hope someone can help me.

Best regard Dirk

Maybe use input_pullup for your button and check for a button press being low. You'll have to wire your button correspondingly too.

The way the code is now it keeps looping.

In other words, the switch doesn't work. The code is fine, it can be improved don't change it yet. Have you tested the switch with some simple code to see if it goes on/off?

You begin() a serial object and then don't use it.

Oh I'm sorry. I forgot something.

buttonpin is a 5v input from my computer when I turn the computer on

dhk123:
Oh I'm sorry. I forgot something.

buttonpin is a 5v input from my computer when I turn the computer on

Then call it "computerInput" instead of "buttonpin". The IDE is a text editor, too. :slight_smile: Please provide a wiring diagram.

Edit - and if you have a relay pin, call it a relay pin, not a "ledPin".

here's the schematic

To make it work reliable you have to connect the ground of the computer with the ground of the arduino

Or if you don't want this you would have to use an optocoupler.

What does the +5V and Ground and 10 kOhm-resistor do?
What kind of relais are you using?
relais pull quite some current. And if the coil is switched off a voltage-spike occurs which could damage your board if you don't use a freewheeling diode anti-parall connected to the relay's coil

best regards Stefan

It's a pull down resistor.

The relais at the moment is just a standard module.

550x485.jpg

550x485.jpg

You shouldn’t connect 5V from an external device directly to an Arduino input pin (pin 2 in this case). Especially a 5V power source. You need to add at least a series resistor for protection of the Arduino. Your “pull down” resistor makes no sense. It’s in parallel with the power supply, so can’t have any pull down effect. All is does is drain a tiny bit of power from the supply.

When you draw a schematic, there should be no mysteries. Any line that goes into a box must be labelled, otherwise it is useless. Nobody can tell where the wires to your relay module are connected.

It's a pull down resistor.

What makes you think that, and why would it be required wired as it is ?