How Can I Detect Button Pressing?


Hey everyone, I'm relatively new to the Arduino community, and there's a project I'm hoping to work on sometime, so I'm using Tinkercad Circuits (as seen in the image above) to run a simulation of my project before buying the kinds of parts I'll need for this project. I got the Arduino to detect the potentiometer's position, but now I'm trying to figure out how I can get the Arduino to detect when the button is being pressed and released. What should I do?

I look forward to hearing an answer to this question.

PS. Here's the code I used for the Arduino thus far:
// C++ code
//
void setup()
{
Serial.begin(9600);
}

void loop()
{
int potValue = analogRead(0);
int butValue = analogRead(1);
Serial.println("TURN: ");
Serial.println(potValue);
Serial.println("PRESS: ");
Serial.println(butValue);
}

Start of by wiring your push button correctly.

Wire it with one contact wired to ground and the other to the input, wire across the diagonal of the switch when it straggles the gap in the middle of the bread board.

Then set the pinMode for that pin to INPUTPULLUP in your setup function.

Then read the pin with a digital read, or an analog read, and if it reads LOW the button is pushed, if it reads HIGH the button is not pushed.

Use the returned values in an if statement to decide what to print.

Your code as written will just print the same thing all the time no matter if the button is pressed or not.

Is there no Tinkercad forum?

If you want the arduino to understand when the button is pressed, you have to use digitalread() function. Kindly check the simplest example here:

That is a very bad example, a lot of the official examples are very bad.

For the full reason why it is bad see
http://www.thebox.myzen.co.uk/Tutorial/Inputs.html

There's lots of information and tutorials about pressing buttons, here's mine:

This state change detection tutorial will show how to wire the switch and how to detect the switch being pressed and released.

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