Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8015

Python • Re: Cleanest way to turn on GPIO based on input string

$
0
0
Here an example:

inputs.csv:

Code:

10,button1,up11,button2,up12,button3,down
outputs.csv:

Code:

13,relais1,014,relais2,1

Code:

import csvfrom pathlib import Path# Mock of RPi.GPIO, useful if you don't have real hardware to testimport Mock.GPIO as GPIO# you want to import this:# import from RPi import GPIOSCRIPT_DIR = Path(__file__).parentINPUTS = SCRIPT_DIR / "inputs.csv"OUTPUTS = SCRIPT_DIR / "outputs.csv"def setup_inputs(file):    inputs = {}    with open(file) as fd:        reader = csv.reader(fd)        for pin, name, pull in reader:            pin = int(pin)            inputs[name] = pin            inputs[pin] = name            if pull == "up":                pull = GPIO.PUD_UP            elif pull == "down":                pull = GPIO.PUD_DOWN            elif pull == "off":                pull = GPIO.PUD_OFF            else:                raise ValueError(f"Wrong pull: {pull}")                        GPIO.setup(pin, GPIO.IN, pull_up_down=pull)    return inputsdef setup_outputs(file):    outputs = {}    with open(file) as fd:        reader = csv.reader(fd)        for pin, name, value in reader:            pin = int(pin)            value = int(value)            outputs[name] = pin            outputs[pin] = name            GPIO.setup(pin, GPIO.OUT, value)    return outputsdef setup_gpio():    GPIO.setmode(GPIO.BCM)    inputs = setup_inputs(INPUTS)    outputs = setup_outputs(OUTPUTS)    return inputs, outputsdef main():    inputs, outputs = setup_gpio()    print(inputs)    print(outputs)    # this doesn't work with Mock.GPIO, but it should work with RPi.GPIO on a RPi    # GPIO.output(outputs["relais1"], 1)    # GPIO.output(outputs["relais2"], 0)    # the mock always return None    # with RPi.GPIO an int should return    # print(GPIO.input(inputs["button1"]))    # print(GPIO.input(inputs["button2"]))    # you can also use Pin numbers, because of the double assignment of the dict    print(inputs["button1"])    # button1 is 10    print(inputs[10])    if __name__ == "__main__":    main()

But if you plan to use a newer RPi, then RPi.GPIO does no longer work. Use gpiozero instead. It has abstractions for different libraries.

Statistics: Posted by DeaD_EyE — Mon Mar 24, 2025 9:46 am



Viewing all articles
Browse latest Browse all 8015

Trending Articles