Black Lives Matter - Action and Equality. ... Adafruit is open and shipping.

Newbie Help
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Newbie Help

by imagiro on Fri Nov 07, 2008 10:44 am

I hope this is the right place to be asking newbie questions. This is basically my first programming language and my first program. And the problems begin... Here is what I am trying to do. I have a momentary switch hooked up and an led. When you press the button, it determines if the light is on or off and switches it's state.
Code: Select all | TOGGLE FULL SIZE
int Led13 = 13;
int Switch = 12;
int State = 0;
int SW = 0;

void setup() {
  pinMode(Led13, OUTPUT);
  pinMode(Switch, INPUT);

void loop() {
//  State == 0;
  SW = digitalRead(Switch);
  if (State == 0 && SW == HIGH) {
    digitalWrite(Led13, HIGH);
   State = 1; }
  else if (State == 1 && SW == HIGH) {
    digitalWrite(Led13, LOW);
   State = 0;
  } else {
    digitalWrite(Led13, HIGH);

After it uploads, it blinks. When I press the button, it turns on when I press the button. When it is released, it goes back to blinking. Help Please.
Posts: 13
Joined: Fri Nov 07, 2008 1:16 am

Re: Newbie Help

by westfw on Fri Nov 07, 2008 11:44 am

I think what you are missing is that loop() gets called over and over again, regardless of whether there has been any activity on the switch. So if the button is pressed, you set your state and light the LED, and then loop gets called again and you zero state and turn off the LED (etc) - when the button is pressed, you don't have the LED ON, you have it toggling at a rate that is too fast to see. When you release the button, you might stay in your state-based code for one more iteration, but then you'll fall out the bottom into the original blink code again.
You'll typically need another set of state values for the button, and examine/toggle the LED state only when the button state goes from "unpressed" to "pressed."

Otherwise it looks pretty nice for a first program.

You might want to note that the arduino (and microcontroller programming in general) is DIFFERENT in this respect than a desktop computer. On the desktop, the operating system (ie windows) would handle some of the details, and your program would receive "events" and wake up "once" per mouse-button click (for example.)

Posts: 1655
Joined: Fri Apr 27, 2007 1:01 pm
Location: SF Bay area

Please be positive and constructive with your questions and comments.