Arduino Projects

Arduino Uno R4 Minima #3: Push button

Push button with Arduino Uno R4:

Push Button with Arduino Uno R4 Minima- In the previous article, we used an RGB Led module with the Arduino Uno R4 Minima board. This time, we will also use a Push button along with this RGB Led module. I have already explained the Pinout and interfacing of the Push button module. For the connections, you can follow this Circuit diagram.

Push button with Arduino Uno R4

And let me remind you one more time, if you don’t have the Arduino Uno R4 minima board there is no need to worry, you can also use the Arduino Uno R3 or even you can use the Arduino Nano. Let’s go ahead and start with our first example.




Amazon Links:

SunFounder Ultimate Sensor Kit

Arduino Uno R4 Minima Board

Other Tools and Components:

Top Arduino Sensors:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!



Push button example 1:

The purpose of the program is to detect the state of a push button connected to the Arduino and print a message to the Serial monitor based on whether the button is pressed or released.

Push button press detection Program:

const int buttonPin = 2;

void setup() {

pinMode(buttonPin, INPUT);
}

void loop() {
int buttonState = digitalRead(buttonPin);

if (buttonState == LOW) {
Serial.println("Button Pressed");
  } else {
Serial.println("Button Released");
  }
delay(500);
}

Explanation:

const int buttonPin = 2;

This line declares a constant integer variable buttonPin and assigns it the value 2. This means the push button is connected to digital pin 2 on the Arduino.

void setup() {

  pinMode(buttonPin, INPUT);

}

The setup() function is called once when the Arduino starts. It sets up the button pin as an INPUT. This configures the Arduino to read the state of the pin.

void loop() {

  int buttonState = digitalRead(buttonPin);

  ...

}

The loop() function runs continuously after the setup() function. Inside this loop, the program reads the state of the button using digitalRead(buttonPin), which returns the state of the button (HIGH or LOW) and stores it in the buttonState variable.

if (buttonState == LOW) {

  Serial.println("Button Pressed");

} else {

  Serial.println("Button Released");

}

Here, the program checks the value of buttonState. If it’s LOW, it means the button is pressed, and “Button Pressed” is printed to the Serial monitor. If not (else), “Button Released” is printed.

delay(500);

Finally, there is a delay(500), which pauses the loop for 500 milliseconds (half a second). This delay prevents the messages from being printed too rapidly and continuously.



Demonstration:

Push button with Arduino Uno R4

You can see, when I press the button, a message ‘button pressed’ is printed on the screen, and when I release the button, a message ‘button released’ is printed. I know this task might feel very basic to you, like it’s for children, but trust me, this will be useful in almost every project you do in the future. Because if you have learned how to detect the button press and release states, now you can use any digital sensor to print a message on the screen. The main purpose of this example was to read a digital input and then, based on the detection, to print a message on the serial monitor.

Let’s make it a bit complex now.

You can see that when the button is not pressed, it keeps printing the same message over and over again that ‘Button Released’. And when I press the button, it repeatedly prints the same message saying ‘Button Pressed’. I want the message to be printed only once when I press or release the button. So, let’s go ahead and do it.



Push button as a Toggle Switch Example2:

const int buttonPin = 2;  // pushbutton is connected to digital pin 2
int buttonState;          // stores current state of the button
int lastButtonState = LOW;   // stores previous state of the button
bool isOn = false;           // boolean to keep track of the toggle state

void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
  // read the state of the pushbutton
buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
if (buttonState != lastButtonState) {
    // if the state has changed
      if (buttonState == LOW) {
            // if the current state is HIGH, then the button went from off to on:
      isOn = !isOn; // toggle the state
      if (isOn) {
      Serial.println("Button Pressed");
            } else {
      Serial.println("Button Released");
            }
          }
    // Delay a little bit to avoid bouncing
delay(50);
  }

  // save the current state as the last state, for next loop iteration
lastButtonState = buttonState;
}

Explanation:

I have slightly modified the previous code. And as you can see, I have added comments to maximum of the instructions.

const int buttonPin = 2;

this line defines a constant integer for the button pin, indicating that the pushbutton is connected to digital pin 2 on the Arduino.

int buttonState;

The variable buttonState is used to store the current state of the button.

int lastButtonState = LOW;

The variable lastButtonState is used to store the last state of the button. Initially set to LOW.

bool isOn = false;

This is a boolean variable to keep track of the toggle state.




void setup() {

  pinMode(buttonPin, INPUT);

  Serial.begin(9600);

}

You are already familiar with this part of the code.

buttonState = digitalRead(buttonPin);

This line reads the current state of the button.

// compare the buttonState to its previous state

if (buttonState != lastButtonState) {

    // if the state has changed

      if (buttonState == LOW) {

            // if the current state is HIGH, then the button went from off to on:

      isOn = !isOn; // toggle the state

      if (isOn) {

      Serial.println("Button Pressed");

            } else {

      Serial.println("Button Released");

            }

          }

    // Delay a little bit to avoid bouncing

delay(50);

  }

The program checks if the button’s state has changed compared to its previous state.

If the state has changed, it enters the conditional block.

If buttonState is LOW (means if the button is pressed), it toggles the isOn state. This is a way to change the state each time the button is pressed.

Depending on whether isOn is true or false, it prints “Button Pressed” or “Button Released” to the Serial monitor.

delay(50);

This small delay is added to handle debouncing. When a button is pressed, it physically bounces a little and can cause multiple detections. This delay ensures that only one press or release is registered in a short time frame.

lastButtonState = buttonState;

The current button state is saved as the last state for the next loop iteration.



Demonstration:

Push button with Arduino Uno R4

Now you can see the message is printed only once. It doesn’t matter if I keep the button pressed, because until the state of the button changes, another message won’t be printed. This concept of a toggle switch will be quite useful in many of your upcoming projects.

Next, instead of printing a message on the screen, we will turn an LED ON or OFF. When we press the button, the LED will turn ON, and when we press the button again, the LED will turn OFF. So, let’s go ahead and take a look at the programming.

Push button toggle LED program 3:

const int buttonPin = 2;  // pushbutton connected to digital pin 2
int buttonState;          // current state of the button
const int ledPin = 11;    // Blue Led
int lastButtonState = LOW;   // previous state of the button
bool isOn = false;           // boolean to keep track of the toggle state

void setup() {
  
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);

}

void loop() {
  // read the state of the pushbutton
buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
if (buttonState == LOW) {
      // if the current state is HIGH, then the button went from off to on:
isOn = !isOn; // toggle the state
if (isOn) {
digitalWrite(ledPin,HIGH);
      } else {
digitalWrite(ledPin,LOW);
      }
    }
    // Delay a little bit to avoid bouncing
delay(50);
  }

  // save the current state as the last state, for next loop iteration
lastButtonState = buttonState;
}



Explanation:

Again, I slightly modified the program. As you can see, this time I have also defined a Pin for the LED. Although there are three LEDs in the RGB LED module, I will only control one LED. In the circuit diagram, you can see that the Blue LED is connected to pin 11.

The rest of the code is exactly the same. This time, instead of printing messages, I am turning the LED ON/OFF. In the image below you can see the LED is OFF.

Push button with Arduino Uno R4

When I pressed the button the LED turned ON.

Push button with Arduino Uno R4

So, you can see, I am able to turn the LED ON and OFF without any false triggering. If you want to control higher AC/DC loads, you can replace the LED with a relay or a MOSFET. I will explain this in much detail in my upcoming tutorials.

Anyway, now let’s take this project to a slightly more advanced level. In this next example, we will use the push button to turn on each of the three LEDs one by one. So, let’s go ahead and take a look at the programming.



RGB Led Module and Push button example 4:

const int buttonPin = 2;  // Pin connected to the pushbutton
const int R_Pin = 9;     // Pin connected to the red leg of the RGB LED
const int G_Pin = 10;  // Pin connected to the green leg of the RGB LED
const int B_Pin = 11;   // Pin connected to the blue leg of the RGB LED

int buttonState = 0;      // Variable to store the button state
int lastButtonState = 0;  // Variable to store the previous button state
int colorIndex = 0;       // Variable to track the current color index

void setup() {
  
  pinMode(buttonPin, INPUT);
  pinMode(R_Pin, OUTPUT);
  pinMode(G_Pin, OUTPUT);
  pinMode(B_Pin, OUTPUT);

}

void loop() {
  buttonState = digitalRead(buttonPin);

  // Check if the button state has changed
  if (buttonState != lastButtonState) {
    // If the button is pressed, increment the color index
    if (buttonState == HIGH) {
      colorIndex++;

      // Reset the color index if it exceeds the number of colors
      if (colorIndex > 2) {
        colorIndex = 0;
      }

      // Set the color based on the current index
      SetColor(colorIndex);

    }

    // Update the last button state
    lastButtonState = buttonState;
  }
}

// Function to set the color based on the index
void SetColor(int index) {
  // Turn off all colors
  digitalWrite(R_Pin, LOW);
  digitalWrite(G_Pin, LOW);
  digitalWrite(B_Pin, LOW);

  // Set the color based on the index
  if (index == 0) {
    digitalWrite(R_Pin, HIGH);
  } else if (index == 1) {
    digitalWrite(G_Pin, HIGH);
  } else if (index == 2) {
    digitalWrite(B_Pin, HIGH);
  }
}

Explanation:

By looking at this program, you must have gotten the idea that this time I have combined the Led blinking and push button toggle programs. The flow of the program is exactly the same, but this time I have used the concept of a counter. I count the button clicks and then, based on the value, we control the Leds. I have added comments, so I am sure you won’t face any difficulty in understanding this code.

Anyway, this time I have also called a function named SetColor(), in which I have passed colorIndex as an argument.

‘Void’ at the start of the function name means that this function does not have a return type and it takes only one argument as input.

Inside this function, you can see, we are just turning ON the LEDs based on the index number.




Demonstration:

Push button with Arduino Uno R4

After uploading the program, I was able to scroll through RED, GREEN, and BLUE Leds. It worked perfectly and there was no false triggering.

In the next example, we will study Analog Input and PWM ‘Pulse Width Modulation’ in detail. We will use PWM to automatically control the brightness of the RGB Led module, and then we will also control it using a Potentiometer.



Watch Video Tutorial:

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button