How to Debouncing a Button Press in Raspberry pi

In some cases, after you press the button on a switch, the anticipated action happens more than once, since the switch contacts bounce. In that case, you need to write code to de-bounce the switch.  Today I show you How to Debouncing a Button Press in Raspberry pi.  

Components Required :

1.Raspberry pi

2.Breadboard

3. Connecting wire

5.Push Button Switch

6.  5mm  LED 

This book will help you to gain more knowledge of Raspberry pi  Software and Hardware Problems and Solutions

Raspberry Pi Cookbook

Circuit diagram Debouncing Raspberry pi:

shows how to connect a tactile push switch and LED, using a breadboard and jumper wires

push switch and LED to a Raspberry Pi

Code-1

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
switch_pin = 18
led_pin = 23
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led_pin, GPIO.OUT)
led_state = False
old_input_state = True # pulled-up
while True:
    new_input_state = GPIO.input(switch_pin)
    if new_input_state == False and old_input_state == True:
        led_state = not led_state
        old_input_state = new_input_state
        GPIO.output(led_pin, led_state)

The issue is that in the event that the switch contacts bounce, it is just as in case the switch was pressed more than once in exceptionally fast successionIn case they bounce an odd number of times, at that point, things will appear to be Alright. But in case they bounce an even number of times, the two events will toggle the Led on and then straight back off again. You have to ignore any changes after the switch is pressed for a short amount of time, whereas the switch finishes bouncing. The fast and simple way to do usually to introduce a short sleep after the button press is recognized by adding time.sleep command of, say, 0.2 seconds. This delay is probably much higher than vital, strictly speaking. You'll discover that you just can decrease this impressively

Code-2

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
switch_pin = 18
led_pin = 23
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led_pin, GPIO.OUT)
led_state = False
old_input_state = True # pulled-up
while True:
    
     new_input_state = GPIO.input(switch_pin)
     if new_input_state == False and old_input_state == True:
         led_state = not led_state
         time.sleep(0.2)
         old_input_state = new_input_state
         GPIO.output(led_pin, led_state)

If you want to know more about raspberry pi then click on the link below

RASPBERRY PI TUTORIALS FOR BEGINNERS

No comments

Theme images by Dizzo. Powered by Blogger.