'Why do my arguments given in the terminal not get parsed by argparse correctly?
I have a question about my code in python. I am supposed to define an input pin and an output pin in the command line. When the input pin gets an input (High or Low), it is supposed to pass it to the output pin. To test my code, I connected a button to my input pin and an LED to my output pin. I want to define my input pin and output pin in the command line using argparse, so I do not have to change the pins in the code every time I change the pins physically. My code worked before using argparse, but now after implementing argparse it does not do what it is supposed to (does nothing). My code looks like this:
import RPi.GPIO as GPIO
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('pin_in', type = int, help = 'Possible output pins: 3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29, 31, 32, 33, 35, 36, 37, 38, 40')
parser.add_argument('pin_out', type = int, help = 'Possible input pins: 3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29, 31, 32, 33, 35, 36, 37, 38, 40')
args = parser.parse_args()
GPIO.setmode(GPIO.BOARD) #set pin numbering style
GPIO.setup(args.pin_out,GPIO.OUT) #set pin_out as output pin
GPIO.setup(args.pin_in,GPIO.IN, pull_up_down = GPIO.PUD_UP) #set pin_in as input pin
def inputToOutput(pin_in, pin_out): #this method is supposed to read pin_in status (HIGH or LOW) and pass it to the output pin pin_out
if GPIO.input(pin_in) == GPIO.LOW:
GPIO.output(pin_out, GPIO.LOW)
else:
GPIO.output(pin_out, GPIO.HIGH)
if __name__ == '__main__':
GPIO.add_event_detect(args.pin_in, GPIO.BOTH, callback = lambda x: inputToOutput(args.pin_in, args.pin_out)) #this detects either a falling or rising edge and if an edge is detected, calls the inputToOutput method;
#add_event_detect syntax is (input channel, rising/falling/both edges, callback function)
Name of my file is PinMonitor_argparse.py and I run the file in the terminal by:
python3 PinMonitor_argparse.py --pin_in 35 --pin_out 15
I first tried to pass the 35 and 15 without writing --pin_in and --pin_out first like
python3 PinMonitor_argparse.py 35 15
and got the notification in the terminal:
usage: PinMonitor_argparse.py [-h] [--pin_in PIN_IN] [--pin_out PIN_OUT]
So I added the --pin_in and --pin_out and the error
error: unrecognized arguments: 35 15
was gone. Now I do not get any error notification, but the code is still not changing the output pin status depending on the input pin status.
I am thankful for any suggestion in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|