Today, I've started a decision maker, using a Arduino UNO R3, a button and a RGB led. This project makes a decision for you (yes, no, or maybe) when you don't know your own decision about something.

The code I used in the project is the following one (written by me):

#define out OUTPUT
#define in INPUT
#define H HIGH
#define L LOW

int red = 2;
int green = 3;
int blue = 4;

int randomValue = 0;

int button = 5;
int buttonState = 0;

void setup(){
    pinMode(red, out);
    pinMode(green, out);
    pinMode(blue, out);

    pinMode(button, in);   

void loop(){
    buttonState = digitalRead(button);
    if(buttonState == H){
        randomValue = random(0,4);
        if(randomValue == 1){
            digitalWrite(red, H);
            digitalWrite(red, L);
        if(randomValue == 2){
            digitalWrite(green, H);
            digitalWrite(green, L);
        if(randomValue == 3) {
            digitalWrite(blue, H);
            digitalWrite(blue, L);


The connections are correct, and the code also. The problem is: when I push the button, the LED starts showing random colors, and what I want is for the LED to show one color per push.

What can I do?


There is one basic concept that you are lacking. At the moment you are looking to see if the button is pressed, not when the button has been pressed.

Instead of just looking to see if it is HIGH you need to look if it was LOW but is now HIGH. It's that transition from LOW to HIGH that you need to use as your trigger for when to set the LED colour, and that means remembering the state of the button the last time you went through the loop.

buttonState = digitalRead(button);
if (buttonState != oldButtonState) {
    oldButtonState = buttonState;
    if(buttonState == H) {
        // Do your stuff

oldButtonState is defined the same as buttonState.

  • oldButtonState is a new variable? – spund3 Jan 2 '16 at 18:23
  • Of course. What else could it be? – Majenko Jan 2 '16 at 18:24
  • You may also need to debounce the button – if you still see multiple changes before the decision is finalized :-) Unless, of course, you consider a bit of dithering to be a good thing… – dlu Jan 3 '16 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.