Python Forum

Full Version: class Update input (Gpio pin raspberry pi)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi (Newbie here self taught first in C - Arduino and now try to learn Python but with my mind thinking like programing C and want to change that to pythonic way of thinking)

i want to print on screen my gpio input .
with simple python code with "def" only i can do that easy

But i want to start using classes and so i tried the code below but i can print the Gpio state of what it is when the loop starts. i am not getting any changes
if the loop starts and the button is not pressed then i get always "0" even if i press the button
if the loop starts and have the button pressed then i am getting always "1" even if i stop pressing the button

What i am doing wrong?
thanks in advance

My code :

import RPi.GPIO as GPIO
import time
GPIO.cleanup()
Button_1 = 23  # incoming signal from a button
# OutPut = 21  # Led for output
################################################################################################
###############################  SETUP GPIO METHOD  ############################################
################################################################################################
# GPIO.setmode(GPIO.BOARD) # # NUMBER OF PINS BASED ON BOARD NUMBERING
GPIO.setmode(GPIO.BCM)  # NUMBER OF PINS BASED ON IC
#############################  SETUP GPIO PINS INPUT  ##########################################
GPIO.setup(Button_1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#GPIO.setup(Button_1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
############################  SETUP GPIO PINS OUTPUT  ##########################################
# GPIO.setup(OutPut, GPIO.OUT)
# GPIO.output(OutPut, GPIO.LOW)
################################################################################################
class Status:
    def __init__(self):
        self.button1 = GPIO.input(Button_1)
    def getStatus(self):
        return self.button1

def main():
    while True:
        print(status.getStatus())

print("Starting....")
time.sleep(2.0)
status = Status()
main()
Classes aren't "Pythonic", they are object oriented. You can do object oriented programming in Python, C++ and even C.

Your program is doing this:
status = GPIO.input("Button_1")
while True:
    print(status)
I would write your code more like this:
import RPi.GPIO as GPIO
import time

class Button:
    """A GPIO input"""
    def __init__(self, pin):
        self.pin = pin
        GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    def status(self):
        """Return state of input"""
        return GPIO.input(self.pin)


def main():
    print("Starting....")
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    button1 = Button(23)
    time.sleep(2.0)
    while True:
        time.sleep(2.0)
        print(button1.status())
 
if __name__ == "__main__":
    main()
Thanks for the HELP !! Heart