{"id":23,"date":"2015-06-15T21:22:01","date_gmt":"2015-06-15T21:22:01","guid":{"rendered":"http:\/\/madgyver.de\/?p=23"},"modified":"2024-02-08T09:23:18","modified_gmt":"2024-02-08T09:23:18","slug":"arduino-taster-abfragen-und-entprellen","status":"publish","type":"post","link":"https:\/\/madgyver.de\/en\/arduino-taster-abfragen-und-entprellen\/","title":{"rendered":"Handling Button Presses and Debounce Methods"},"content":{"rendered":"<p>Often, you want to control an Arduino using a button. Fortunately, connecting a button is straightforward, and the Arduino IDE even provides a pre-made sketch that you can find under<\/p>\n<p><strong>Examples -&gt; 02.Digital -&gt; Button.<\/strong><\/p>\n<p>Here is the source code:<\/p>\n<p>[code]<br \/>\n\/*<br \/>\n Button<\/p>\n<p> Turns on and off a light emitting diode(LED) connected to digital<br \/>\n pin 13, when pressing a pushbutton attached to pin 2.<\/p>\n<p> The circuit:<br \/>\n * LED attached from pin 13 to ground<br \/>\n * pushbutton attached to pin 2 from +5V<br \/>\n * 10K resistor attached to pin 2 from ground<\/p>\n<p> * Note: on most Arduinos there is already an LED on the board<br \/>\n attached to pin 13.<\/p>\n<p> created 2005<br \/>\n by DojoDave<br \/>\n modified 30 Aug 2011<br \/>\n by Tom Igoe<\/p>\n<p> This example code is in the public domain.<\/p>\n<p> http:\/\/www.arduino.cc\/en\/Tutorial\/Button<br \/>\n *\/<\/p>\n<p>\/\/ constants won&#8217;t change. They&#8217;re used here to<br \/>\n\/\/ set pin numbers:<br \/>\nconst int buttonPin = 2; \/\/ the number of the pushbutton pin<br \/>\nconst int ledPin = 13; \/\/ the number of the LED pin<\/p>\n<p>\/\/ variables will change:<br \/>\nint buttonState = 0; \/\/ variable for reading the pushbutton status<\/p>\n<p>void setup() {<br \/>\n \/\/ initialize the LED pin as an output:<br \/>\n pinMode(ledPin, OUTPUT);<br \/>\n \/\/ initialize the pushbutton pin as an input:<br \/>\n pinMode(buttonPin, INPUT);<br \/>\n}<\/p>\n<p>void loop() {<br \/>\n \/\/ read the state of the pushbutton value:<br \/>\n buttonState = digitalRead(buttonPin);<\/p>\n<p> \/\/ check if the pushbutton is pressed.<br \/>\n \/\/ if it is, the buttonState is HIGH:<br \/>\n if (buttonState == HIGH) {<br \/>\n \/\/ turn LED on:<br \/>\n digitalWrite(ledPin, HIGH);<br \/>\n }<br \/>\n else {<br \/>\n \/\/ turn LED off:<br \/>\n digitalWrite(ledPin, LOW);<br \/>\n }<br \/>\n}<br \/>\n[\/code]<\/p>\n<p>In addition to an Arduino, you&#8217;ll need a button and a resistor. The resistor connects pin 2 to ground, pulling the voltage at the pin to 0V. When you press the button, the pin is connected to the supply voltage (5V), and the voltage at the pin quickly rises to 5V. This voltage change is detected by the Arduino and can be read using the digitalRead function.<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"http:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster_Steckplatine.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-62\" src=\"http:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster_Steckplatine-300x254.png\" alt=\"\" width=\"300\" height=\"254\" srcset=\"https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster_Steckplatine-300x254.png 300w, https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster_Steckplatine-768x650.png 768w, https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster_Steckplatine-1024x866.png 1024w, https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster_Steckplatine.png 1755w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>The sketch sets pin 2 to input mode and pin 13 to output mode. Pin 2 is where the button is connected, and on the Arduino, there&#8217;s already an LED built into pin 13. In the loop, it continuously checks the state of pin 2 using <code>digitalRead<\/code>. The variable <code>buttonState<\/code> is then set to 0 or 1, depending on the value <code>digitalRead<\/code> returns. If <code>buttonState<\/code> is set to 1, the LED is turned on; otherwise, it&#8217;s turned off..<\/p>\n<h2><strong>Single Button Presses<\/strong><\/h2>\n<p>However, this doesn&#8217;t allow toggling between on and off states with a single button press. To achieve this, you can use the following code:<\/p>\n<p>[code]<br \/>\n\/*<br \/>\n  Button<\/p>\n<p> Turns on and off a light emitting diode(LED) connected to digital<br \/>\n pin 13, when pressing a pushbutton attached to pin 2.<\/p>\n<p> The circuit:<br \/>\n * LED attached from pin 13 to ground<br \/>\n * pushbutton attached to pin 2 from +5V<br \/>\n * 10K resistor attached to pin 2 from ground<\/p>\n<p> * Note: on most Arduinos there is already an LED on the board<br \/>\n attached to pin 13.<\/p>\n<p> *\/<\/p>\n<p>\/\/ constants won&#8217;t change. They&#8217;re used here to<br \/>\n\/\/ set pin numbers:<br \/>\nconst int buttonPin = 2;     \/\/ the number of the pushbutton pin<br \/>\nconst int ledPin =  13;      \/\/ the number of the LED pin<\/p>\n<p>\/\/ variables will change:<br \/>\nint buttonState = LOW;         \/\/ variable for reading the pushbutton status<br \/>\nint buttonread = 0;<\/p>\n<p>void setup() {<br \/>\n  \/\/ initialize the LED pin as an output:<br \/>\n  pinMode(ledPin, OUTPUT);<br \/>\n  \/\/ initialize the pushbutton pin as an input:<br \/>\n  pinMode(buttonPin, INPUT);<br \/>\n  Serial.begin(9600);<br \/>\n}<\/p>\n<p>void loop() {<br \/>\n  \/\/ read the state of the pushbutton value:<br \/>\n  buttonread = digitalRead(buttonPin);<\/p>\n<p>  \/\/ check if the pushbutton is pressed.<br \/>\n  \/\/ if it is, the buttonState is HIGH:<br \/>\n  if (buttonread == HIGH) { \/\/Check if Button was pressed before and being pressed now<\/p>\n<p>    if (buttonState == LOW)<br \/>\n    {<br \/>\n      \/\/ turn LED on:<br \/>\n      digitalWrite(ledPin, HIGH);<br \/>\n      buttonState = HIGH;<br \/>\n      Serial.println(&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;Button pressed&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;);<br \/>\n    }<br \/>\n  }<br \/>\n  else {<br \/>\n    if (buttonState == HIGH) {<br \/>\n      digitalWrite(ledPin, LOW);<br \/>\n      buttonState = LOW;<br \/>\n    }<br \/>\n  }<br \/>\n}<\/p>\n<p>[\/code]<\/p>\n<ol>\n<li>At the beginning, <code>buttonState<\/code> is initialized to <code>LOW<\/code>. This variable keeps track of whether the button has been pressed before, and <code>LOW<\/code> indicates that it hasn&#8217;t been pressed yet.<\/li>\n<li>The code then uses <code>digitalRead<\/code> to check the button&#8217;s state. If <code>buttonState<\/code> is already in the <code>LOW<\/code> state, the LED is turned on, <code>buttonState<\/code> changes to <code>HIGH<\/code>, and we receive a message via the Serial Port using the <code>Serial.println<\/code> command. Even when releasing the button, the LED remains on.<\/li>\n<li>\u00a0If you press the button again, <code>buttonState<\/code> is already in the <code>HIGH<\/code> state, and the <code>else if<\/code> condition is met and executed. Within this condition, <code>buttonState<\/code> is set back to <code>LOW<\/code>, and the LED is turned off.<\/li>\n<\/ol>\n<p>In essence, this works, but&#8230;<\/p>\n<div class=\"w-full text-token-text-primary\" data-testid=\"conversation-turn-7\">\n<div class=\"px-4 py-2 justify-center text-base md:gap-6 m-auto\">\n<div class=\"flex flex-1 text-base mx-auto gap-3 md:px-5 lg:px-1 xl:px-5 md:max-w-3xl lg:max-w-[40rem] xl:max-w-[48rem] group final-completion\">\n<div class=\"relative flex w-full flex-col lg:w-[calc(100%-115px)] agent-turn\">\n<div class=\"flex-col gap-1 md:gap-3\">\n<div class=\"flex flex-grow flex-col max-w-full\">\n<div class=\"min-h-[20px] text-message flex flex-col items-start gap-3 whitespace-pre-wrap break-words [.text-message+&amp;]:mt-5 overflow-x-auto\" data-message-author-role=\"assistant\" data-message-id=\"4ef497dd-99c5-4e80-96d8-b3107f0a7734\">\n<div class=\"markdown prose w-full break-words dark:prose-invert light\">\n<p>Frequently, multiple messages are sent via the serial interface even though the button was pressed only once. This shouldn&#8217;t happen in theory; even if you hold down the button, the code for <code>buttonState == LOW<\/code> should only execute once.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p><a href=\"http:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Button_prellen.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-63\" src=\"http:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Button_prellen-300x252.png\" alt=\"\" width=\"300\" height=\"252\" srcset=\"https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Button_prellen-300x252.png 300w, https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Button_prellen.png 459w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>The image above, for example, is after a single button press. What happened?<\/p>\n<p>&nbsp;<\/p>\n<h2>Bouncing<\/h2>\n<p>When you press the button, you close the electrical circuit, but this doesn&#8217;t happen instantly. The mechanical components inside the button are not perfect, and it may take a little time for the circuit to fully close. This behavior is known as &#8220;bouncing.&#8221; As you can imagine, this is quite problematic. For instance, a keyboard might produce multiple characters in rapid succession with a single keypress. Correcting this behavior is called &#8220;debouncing,&#8221; and there are several approaches to achieve it, both through electrical and software means.<\/p>\n<p>The simplest software solution involves waiting for a brief moment after reading the button. Then, if the button was in the <code>HIGH<\/code> state, read the button again. If the button is still in the <code>HIGH<\/code> state, the Arduino can be quite sure that it was indeed a genuine button press.<\/p>\n<p>[code]<br \/>\nif (buttonread == HIGH) { \/\/Check if Button was pressed before and being pressed now<br \/>\n    delay(5);<br \/>\n    if ((buttonState == LOW) &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; (digitalRead(buttonPin)) )<br \/>\n    {<br \/>\n      if (digitalRead(buttonPin)) {<br \/>\n        \/\/ turn LED on:<br \/>\n        digitalWrite(ledPin, HIGH);<br \/>\n        buttonState = HIGH;<br \/>\n        Serial.println(&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;Button pressed&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;);<br \/>\n      }<br \/>\n    }<br \/>\n  }<br \/>\n[\/code]<\/p>\n<p>The exact duration of the wait depends on the specific situation and is not particularly critical. Typically, a delay of 5 to 50 milliseconds is sufficient.<\/p>","protected":false},"excerpt":{"rendered":"<p>Often, you want to control an Arduino using a button. Fortunately, connecting a button is straightforward, and the Arduino IDE&hellip;<\/p>\n","protected":false},"author":1,"featured_media":67,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[1],"tags":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/madgyver.de\/wp-content\/uploads\/2015\/06\/Arduino-Taster-Entprellen.jpg","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5OAKZ-n","_links":{"self":[{"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/posts\/23"}],"collection":[{"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/comments?post=23"}],"version-history":[{"count":21,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/posts\/23\/revisions"}],"predecessor-version":[{"id":175,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/posts\/23\/revisions\/175"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/media\/67"}],"wp:attachment":[{"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/media?parent=23"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/categories?post=23"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/madgyver.de\/en\/wp-json\/wp\/v2\/tags?post=23"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}