(Arduino UNO) Random Button inputs due to change in code

arduinomotor

(First of all: Sorry for the Title.. I really don't know how to describe my problem in one Sentence)

I'm an arduino beginner. I build a two button control for an electronic motor.

schematic

simulate this circuit – Schematic created using CircuitLab

I wrote a Code to set the Speed with the both buttons (SW4 and SW3) and to display the speed in the serial monitor on my laptop.

It's working perfectly with this code:

void setSpeedButton()
    {

     while(1){ 
      buttonLeftState = digitalRead(buttonLeft);
      buttonRightState = digitalRead(buttonRight);

      if(buttonLeftState == HIGH)
      {
        speed = speed - vChange;
        delay(200);
        if(speed < 0){
          speed = 0;
        }
      }
      if(buttonRightState == HIGH)
      {
        speed = speed + vChange;
        delay(200);
        if(speed > 255){
          speed = 255;
        }
      }
      analogWrite(motor, speed); 

    vDisplay();

  }
 }

vChange is an integer with the value 9, the rest should be clear.

vDisplay() is a void with this code:

void vDisplay()
{
  Serial.print("Speed: ");
  Serial.println(speed);
}

Okay.. So far so good..But now:

if I change the code (first block) and put vDisplay() in both if-query (to display the speed only if it was changed) its like my board is going crazy and randomly changing the speed every few milliseconds and displaying it on the serial monitor…

I really find no solution for this problem. what is causing this problem?

If I forgot to add some informations, please let me know in the comments below.
Thanks everyone for helping or commenting on this!

Best Answer

With the current configuration, your inputs are floating when the buttons aren't pressed. Thus, if no button is pressed, the input could be anything. You have no control. A better solution would be as follows:

schematic

simulate this circuit – Schematic created using CircuitLab

Now, with no button pressed, the input is pulled up to 5V. With a button press, the input is pulled down to ground.