Why did adding Serial.println() to the end of my code fix it?

Hello, I'm new to programming and I am currently going through a book with tutorials utilizing Arduino boards. I am using an UNO R3 and my IDE is using version 2.3.2 on a PC using windows 10. The code listed below is supposed to turn an LED on when a button is pressed, then turn it off when the button is pressed once again.

//turn on led when the button is pressed and off when the button is pressed again

const int LED = 13;   //the pin for the led
const int BUTTON = 7; //the input pin where the button is connected
int val = 0;           //val will be used to store the state of the input pin
int old_val = 0;       // old_val will store last known val
int state = 0;        //0 = led off while 1 = led on

void setup() {
  // put your setup code here, to run once:
    pinMode(LED, OUTPUT);      //tells arsuino led is an output
    pinMode(BUTTON, INPUT);
    Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
    val = digitalRead(BUTTON);    //read input value and store it

    // check whether the input  is HIGH (button pressed)
    // if so change state
    if ((val == HIGH) && (old_val == LOW)){
      state = 1 - state;
    }
      old_val = val;               //val is now stored as old val

    if (state == 1) {
      digitalWrite(LED, HIGH); //turn on led
    } else {
      digitalWrite(LED, LOW);  //tunn off led
    }
}

This code was sporadic and would randomly work. This led me to believe there was a problem with the variables ability to change value correctly. So I attempted to print my variable values on the serial monitor to try and see what was happening. I added Serial.println() to the end of my code (as depicted below) and my code began working as expected with no other changes.

//turn on led when the button is pressed and off when the button is pressed again

const int LED = 13;   //the pin for the led
const int BUTTON = 7; //the input pin where the button is connected
int val = 0;           //val will be used to store the state of the input pin
int old_val = 0;       // old_val will store last known val
int state = 0;        //0 = led off while 1 = led on

void setup() {
  // put your setup code here, to run once:
    pinMode(LED, OUTPUT);      //tells arsuino led is an output
    pinMode(BUTTON, INPUT);
    Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
    val = digitalRead(BUTTON);    //read input value and store it

    // check whether the input  is HIGH (button pressed)
    // if so change state
    if ((val == HIGH) && (old_val == LOW)){
      state = 1 - state;
    }
      old_val = val;               //val is now stored as old val

    if (state == 1) {
      digitalWrite(LED, HIGH); //turn on led
    } else {
      digitalWrite(LED, LOW);  //tunn off led
    }
    Serial.println(state);
}

I am new to programing so I just want to know if there is something wrong with the original code or is there something else I'm not seeing, like a software issue? I appreciate any help you can give.

  • Always show us a good schematic of your proposed circuit.
    Show us good images of your ‘actual’ wiring.
    Give links to components.

  • Scan switches every 50ms to remove switch bounce.

BTW

Ask questions

//   https://forum.arduino.cc/t/why-did-adding-serial-println-to-the-end-of-my-code-fix-it/1301088

//turn on led when the button is pressed and off when the button is pressed again

#define PRESSED    HIGH
#define RELEASED   LOW

#define LEDon      HIGH
#define LEDoff     LOW


const byte LED    = 13;   //the pin for the led
const byte BUTTON = 7;    //the input pin where the button is connected  (closed = HIGH)

byte LEDstate     = LEDoff;

byte lastButton   = 0;

//timing stuff
unsigned long switchesTime;

//                                           s e t u p ( )
//================================================^================================================
void setup()
{
  digitalWrite(LED, LEDoff);
  pinMode(LED, OUTPUT);

  pinMode(BUTTON, INPUT);

} //END of   setup()


//                                            l o o p ( )
//================================================^================================================
void loop()
{
  //========================================================================  T I M E R  switches
  //is it time to scan our switches ?
  if (millis() - switchesTime >= 50ul)
  {
    //restart this TIMER
    switchesTime = millis();

    checkSwitches();
  }


  //================================================
  //other non blocking code goes here
  //================================================


} //END of   loop()


//                                   c h e c k S w i t c h e s ( )
//================================================^================================================
void checkSwitches()
{
  byte currentState;

  //========================================================================  BUTTON
  currentState = digitalRead(BUTTON);

  //================================================
  //has this switch changed state ?
  if (lastButton != currentState)
  {
    //update to the new state
    lastButton = currentState;

    //========================
    //has the switch been pressed ?
    if (currentState == PRESSED)
    {
      if (LEDstate == LEDoff)
      {
        digitalWrite(LED, LEDon);
      }

      else
      {
        digitalWrite(LED, LEDoff);
      }

      //this would also work
      //digitalWrite(LED, digitalRead(LED) ? LEDoff : LEDon);

      LEDstate = !LEDstate;
    }

  } //END of this switch

  //========================================================================  nextSwitch

} //END of   checkSwitches()


//================================================^================================================
2 Likes

One explanation could be that the button switching is noisy and that that the time it takes to do the Serial.println() is long enough to let the button settle.

6 Likes

Seeing as the program worked correctly by adding the Serial.println() function I figured it was safe to assume the wiring was not at fault.
The switch bounce does make sense when you consider the speeds at which the board cycles.
Thanks for the help.

If you don't use a pull-up or pull-down resistor, the input is floating. It will pick up noise form the environment and toggle between LOW and HIGH. Have a look at the image that @LarryD provided.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.