I wrote a crappy Python script that should turn on LEDs connected to the GPIO interface.
import RPi.GPIO as GPIO
import time, sys, json
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
gpioPorts = [4, 9, 22]
for i in range(len(gpioPorts)):
GPIO.setup(gpioPorts[i], GPIO.OUT)
pwm = {}
for i in range(1, len(sys.argv), 2):
if sys.argv[i] == 4 or 9 or 22:
if int(sys.argv[i + 1]) >= 5 and int(sys.argv[i + 1]) <= 100:
pwm["{0}".format(int(sys.argv[i]))] = GPIO.PWM(int(sys.argv[i]), 120)
pwm[sys.argv[i]].start(int(sys.argv[i + 1]))
elif int(sys.argv[i + 1]) == 0:
GPIO.output(int(sys.argv[i]), False)
def getStatus(gpioPorts):
status = {}
for i in range(len(gpioPorts)):
if GPIO.input(gpioPorts[i]) == 0:
status[gpioPorts[i]] = 0
else:
status[gpioPorts[i]] = 1
return status
print(json.dumps(getStatus(gpioPorts)))
When I enter
%Run script.py 4 100 9 20 22 50
in Thonny IDE, it should turn on LED on the GPIO Port 4 with 100% brightness, LED 9 with 20% brightness and LED 22 with 50% brightness. I can change the brightness and everything works fine, but when I enter:
sudo python script.py 4 100 9 20 22 50
in LXTerminal the LEDs flicker and then go out directly. Why does my code work in Thonny but not in the terminal?
EDIT:
import RPi.GPIO as GPIO
import time, sys, json
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
gpioPorts = [4, 9, 22]
for i in range(len(gpioPorts)):
GPIO.setup(gpioPorts[i], GPIO.OUT)
for i in range(1, len(sys.argv), 2):
if sys.argv[i] == 4 or 9 or 22:
if int(sys.argv[i + 1]) == 1:
GPIO.output(int(sys.argv[i]), True)
elif int(sys.argv[i + 1]) == 0:
GPIO.output(int(sys.argv[i]), False)
def getStatus(gpioPorts):
status = {}
for i in range(len(gpioPorts)):
if GPIO.input(gpioPorts[i]) == 0:
status[gpioPorts[i]] = 0
else:
status[gpioPorts[i]] = 1
return status
print(json.dumps(getStatus(gpioPorts)))
I don't need
time.sleep(60)
when I'm not using PWM. I can run the same Code in Thonny and in the terminal. Why do I need "time.sleep ()" in the above code but not in the lower code?