Using a switch to trigger an output for a set time

I am trying to control the release of a door catch and light the leds in the switch at the same time.

I have a relay module hooked up to the electromagnet and 12v supply which I am switching from an output on the arduino (pin 7). I have used the code below to use pin 7 to trigger the relay and at the same time turning on the rgb led in the switch to glow white.(pins 3/4/5)

This works fine but I need the leds/relay to stay on for a set time (10 seconds or so) before turning off I have been experimenting with the delay function but this seems to delay the entire code and not just the light going on.

kit as below;
arduino Uno connected to a relay module, a capacitive touch switch with in-build RGB leds and a electromagnet hooked up to a seperate 12v power supply (via the aforementioned relay )

How do I make this happen or do I need to use the millis function?

code as below which works but need to add the delay

int switchstate = 0;

void setup(){
pinMode(3, OUTPUT); //red LED
pinMode(4, OUTPUT); //green LED
pinMode(5, OUTPUT); //blue LED
pinMode(2, INPUT); //button
pinMode(7, OUTPUT); //output to trigger relay
void loop(){
switchstate = digitalRead(2);//button is on/off switch

if (switchstate ==LOW){ //button pressed
digitalWrite(7, HIGH); //NC relay deactivated
analogWrite(3, 255); //red LED on
analogWrite(4, 255); //green LED on
analogWrite(5, 255); //blue LED on

else  {//button not pressed
digitalWrite(7, LOW);  //NC relay activated
analogWrite(3, 0); //red LED off
analogWrite(4, 0); //green LED off
analogWrite(5, 0); //blue LED off

You need to use millis() to manage the timing without blocking. This is illustrated in Several Things at a Time

Briefly, you save the value of millis() when the LED is turned on and then keep checking the interval between the saved value and the most recent value of millis(). Something like

if (millis() - ledOnMillis >= interval) {
    // turn off LED


Thanks R, Ill look into millis() as you can probably tell I haven't got a clue what i'm doing but at least i don't have to waste time playing around with 'delay'


Generally that happens when newcomers to programming micro controllers. They don't know a tool is available to them and they struggle with inferior methods to work when something much more elegant exists.

It is usually safe to assume for basic most issues, someone else has already had to deal with first and there exists some internet thread or tutorial or example code.

Keep searching for tools to add to your knowledge pool and everything becomes easy. If all else fails, just give your best attempt at coding something you are diving into, and then ask for help once you have expended your knowledge on the subject and you can't get it to work the way you envisioned.