How to stop a loop?

Hey guys,

I've been playing with my Uno board, and feel I'm getting on well. But I can't stop a loop I want to happen. I only want it to happen once.
Here's the code I've got on the board.

#define BUTTON 2
#define LEDRED 4
#define LEDYELLOW 6
#define LEDGREEN 8

int val =0 ;
int state = 0;

void setup(){
  pinMode(BUTTON, INPUT);
  pinMode(LEDRED, OUTPUT);
  pinMode(LEDYELLOW, OUTPUT);
  pinMode(LEDGREEN, OUTPUT);
  
}

void loop(){
  
  val=digitalRead(BUTTON);
  
  if(val == HIGH){
    state =1 - state;
  }
  
  if(state == 1){
    digitalWrite(LEDRED, HIGH);
    delay (4000);
    digitalWrite(LEDRED, LOW);
    digitalWrite(LEDYELLOW, HIGH);
    delay (2000);
    digitalWrite(LEDYELLOW, LOW);
    digitalWrite(LEDGREEN, HIGH);
    delay (5000);
    digitalWrite(LEDGREEN, LOW);
  }
  
}

The button is momentary. I've tried using the 'else' code, but failed to get the result I wanted.

Cheers for any help,

Mikey C

Put the "loop" code in "setup"
Or, put a "while (1);" at the end of the bit you don't want to run again.

Thanks for answering,

I've tried putting the loop in setup, but it wont verify. I've not seen while(1) function before.

Cheers

I've tried putting the loop in setup, but it wont verify

You've written it wrong.
When I said put the code in setup, I meant just to code in "loop()", not "loop()" itself.

I've not seen while(1) function before.

It isn't a function, it's a loop.

After you press the button you want the led's to run through once? You can make state=0 at the end of the 'if statement' so that it doesn't activate the 'if statement' again until you press the button again.

I've put the while(1) at the end, and it's worked. But now the sequence only works the first time of pressing the button.

Sorry for being a biff.

Cheers mate

I think I've got it now, thank you both very much.

Mikey C

I only want it to happen once.

But now the sequence only works the first time of pressing the button.

Be careful what you wish for :wink:

Lol, very true.