Push a button - LED will go on at a random brightness

Hey there,

New user - started playing around with my Arduino yesterday.

I want to make a simple project - push a button and the LED will go on at a random brightness. See attachment how I connected it.

The problem is that the LED just changes constantly, and only when I push the button does it stop. I can't figure out why.

const int LED = 9;
const int BUTTON = 7;
int val = 0;
int i = 0;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop() {
  
  val = digitalRead(BUTTON);
  
  if (val == HIGH) {
    int i = random(255);
    analogWrite(LED, i);
  }
  
}

Hmm. What is it exactly that you wanted it to do? Stop when you release? Is it a latching switch?

syntaxterror:
Hmm. What is it exactly that you wanted it to do? Stop when you release? Is it a latching switch?

When I press the button, it should pick a random integer and make the LED that bright. When I release it or just don't press again, nothing should happen.

Ah, hold up. You have the input connected through the button to ground. The input won't see a high this way. You could try INPUT_PULLUP rather than INPUT, and then changing the test from HIGH to LOW.

syntaxterror:
Ah, hold up. You have the input connected through the button to ground. The input won't see a high this way. You could try INPUT_PULLUP rather than INPUT, and then changing the test from HIGH to LOW.

That did the trick, thanks. Was there a way to get it to work with my original code if I wired it differently?

Sure, you could fix it in the code as well as on the hardware side, not a problem. What you'd have needed was to remove the GND to switch wire and replace it with a connection from 5V to the switch.

Actually that's half an answer. The problem here is that you've left the input floating, neither high nor low. You'd need to pull it in either direction for a consistent reading, and when the switch isn't closed, it's basically not connected to a thing.

Attached is how it would work.

Grawl:
That did the trick, thanks. Was there a way to get it to work with my original code if I wired it differently?

Yes - wire the other end of the switch to Vcc, and then install a pulldown resistor (say 10k ohm?) between the side of the button going to the Arduino, and ground, to keep it looking "off" when it's off (this is what INPUT_PULLUP does in the other direction - but the MCU's used on most Aruino boards don't have internal pulldowns)