Python Forum
function return boolean based on GPIO pin reading
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function return boolean based on GPIO pin reading
#1
Hi, i am not sure how to express it right but i wonder if there is a way to make a function to return a boolean value based of the Gpio readings

some times i have different functions that need to know if the same pins are "True" before do something.. so i have to type to all of them the same thing again and again...
Quote:while GPIO.input(Switch_3) == True and GPIO.input(Switch_4) == True :


how could make a def to check this one and return a value and call the def every time i want to check the state of them ?

Here is a sample code :

import RPi.GPIO as GPIO
import time
GPIO.cleanup()  # Cleans previous Gpio setup if program crashes without clean it first

Switch_1 = 21  # Switch that read "1" - True when is the normal / working
Switch_2 = 20  # Switch that read "1" - True when is the normal / working
Switch_3 = 23  # Switch that read "1" - True when is the normal / working
Switch_4 = 24  # Switch that read "1" - True when is the normal / working

#  SETUP GPIO METHOD  #
GPIO.setmode(GPIO.BCM)
GPIO.setup(Switch_1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(Switch_2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(Switch_3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(Switch_4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def stopAll():
    while GPIO.input(Switch_3) == False or GPIO.input(Switch_4) == False:
        print("Error")
        if GPIO.input(Switch_3) == False:
            print("Switch No3 is Open")
        if GPIO.input(Switch_4) == False:
            print("Switch No4 is Open")

def main():
    while True:
        print("Startin Loop")
        while GPIO.input(Switch_3) == True and GPIO.input(Switch_4) == True :
            print("Do something")
        if GPIO.input(Switch_3) == False or GPIO.input(Switch_4) == False :
            stopAll()

print("Starting....")
time.sleep(2.0)

if __name__ == "__main__":
    main()
Reply
#2
I don't have a raspberry pi, so none of this is tested. I'm also really fuzzy on the pull up/pull down resistors. The assumption in the code below is that the pulldown resistors will make the switch read HIGH when open and LOW when closed. If that is incorrect, it is easy to fix in the Button.__init__() method.
import RPi.GPIO as GPIO
import time

class GP_Input:
    """A GPIO input"""
    def __init__(self, pin, on=GPIO.HIGH, pull_up_down=None):
        self.pin = pin
        self.on = on
        GPIO.setup(pin, GPIO.IN, pull_up_down=pull_up_down)
 
    def status(self):
        """Return state of input"""
        return GPIO.input(self.pin) == self.on

    def is_on(self):
        """Return True if current state == on"""
        return self.status()

    def is_off(self):
        """Return True if current state is off"""
        return not self.status()


class Button(GP_Input):
    """A GPIO input with pull down resistor"""
    def __init__(self, pin):
        # State when button pressed/closed will be LOW
        super().__init__(pin, GPIO.LOW, GPIO.PUD_DOWN)


class InputGroup:
    """A group of inputs.  Can treat like 1 signal."""
    def __init__(self, *inputs):
        self.inputs = inputs

    def status(self):
        """Return on status for each input"""
        return [input.is_on() for input in self.inputs]

    def all_on(self):
        """Return True if all inputs are on"""
        return all(self.status())

    def all_off(self):
        """Return True if all inputs are off"""
        return not any(self.status())


def main():
    print("Starting....")
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    switch_group = InputGroup(Button(23), Button(24))
    time.sleep(2.0)

    while True:
        print("Startin Loop")
        while switch_group.is_on():
            print("Do something")
        s3_closed, s4_closed = switch_group.status()
        if not s3_closed:
            print("Switch No3 is Open")
        if not s4_closed:
            print("Switch No4 is Open")

  
if __name__ == "__main__":
    main()
This example adds inheritance to my previous example in your other thread. Inheritance is another object oriented programming principle, like classes. Inheritance lets you create new classes that inherit behavior from another class. In this example the GP_Input class, a generic GPIO input class, is inherited by Button, a type of input that uses the pull up/pull down resistors. Button "inherits" the state(), is_on() and is_off() methods from the GP_Input class.

InputGroup also uses GP_Input, but this time the relationship aggregate, not inheritance. InputGroup does not inherit anything from GP_Input. It uses GP_Input (or subclasses of GP_Input) objects. The InputGroup lets you test the state of multiple inputs using a single command. This is more generic than writing a function each time you want to work with a group of inputs.
caslor likes this post
Reply
#3
Thank you for the Help and the time you spend to re-write the code in the manner to understand what i have to do
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  nested function return MHGhonaim 2 608 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,277 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  class Update input (Gpio pin raspberry pi) caslor 2 788 Jan-30-2023, 08:05 PM
Last Post: caslor
  Webhook, post_data, GPIO partial changes DigitalID 2 984 Nov-10-2022, 09:50 PM
Last Post: deanhystad
  Need to parse a list of boolean columns inside a list and return true values Python84 4 2,102 Jan-09-2022, 02:39 AM
Last Post: Python84
  return vs. print in nested function example Mark17 4 1,738 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  Exit function from nested function based on user input Turtle 5 2,896 Oct-10-2021, 12:55 AM
Last Post: Turtle
  Help with WebSocket reading data from anoter function korenron 0 1,328 Sep-19-2021, 11:08 AM
Last Post: korenron
  How to invoke a function with return statement in list comprehension? maiya 4 2,824 Jul-17-2021, 04:30 PM
Last Post: maiya
  Function - Return multiple values tester_V 10 4,438 Jun-02-2021, 05:34 AM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020