Looping code?

Hi I am after some help.
My relay is constantly looping and I am after some solutions in my code.
It is meant to run the relay for 10 seconds once the Arduino Uno boots up. Then it is supposed to only activate when the switch is clicked. My code is below and my wiring is attached.

My code:

int val = 0;
int switchPin = 4;
int relayPin = 7;
int readerPin = 2;

void setup() {
pinMode(switchPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);

Serial.begin(9600);

digitalWrite(switchPin, HIGH);

delay(5000);
Serial.println("--------------------");
digitalWrite(relayPin, HIGH);
Serial.println("FLUSHING STARTED");
delay(5000);
Serial.println("FLUSHING");
delay(5000);
digitalWrite(relayPin, LOW);
Serial.println("FLUSHING STOPPED");
Serial.println("--------------------");
}

void loop() {
val = digitalRead(switchPin);
Serial.println(val);

if (val == 0);
{
  digitalWrite(relayPin, HIGH);
  delay(10000);
  digitalWrite(relayPin, LOW);
}
}

Moderator edit:
</mark> <mark>[code]</mark> <mark>

</mark> <mark>[/code]</mark> <mark>
tags added.

Your circuit does not match the pin assignment statements in your code. Try wiring your switch between a pin and ground, then use INPUT_PULLUP in pinMode(). Read up on the technique known as "millis timing" or "blink without delay" or "several things at the same time", because those ten second delay statements are freezing your code for most of the time that it's executing.

Perhaps put the first closure of the relay in the setup() part of the code. Then in loop(), start counting millis when the button is pressed, and close the relay. Once the count reaches 10 seconds, reset the timer and open the relay.

I have no idea how to use millis timing. Even after an hour of research!
Can anyone teach me?

daniel_dim_15:
I have no idea how to use millis timing. Even after an hour of research!
Can anyone teach me?

http://www.thebox.myzen.co.uk/Tutorial/State_Machine.html

Please correct your post with </> code tags.

The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. It may help with understanding the technique.

Have a look at Using millis() for timing. A beginners guide if you need more explanation.

...R

How many times do you need to ask the same question? Need help with loops and switches - Project Guidance - Arduino Forum

Steve

daniel_dim_15:
I have no idea how to use millis timing. Even after an hour of research!
Can anyone teach me?

Using millis() for timing. A beginners guide