I have a code that gets a one or a 0 from the user and will turn an LED on if 1, off if 0. It runs perfect when I run it in the Thonny IDE on the Pi itself. But when I try to run it through putty or even the Pi's terminal it will run everything except the if statements. (Does not print 'LED On/Off' or actually turn on or off the LED).
import RPi.GPIO as GPIO
import time
LEDPin = 17
#Setup
def setup():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) #Set GPIO to BCM numbering
GPIO.setup(LEDPin,GPIO.OUT,initial = GPIO.LOW)
print('setup complete')
def main():
setup()
while 1: #check for keyboard input
KBInput = input('1 for LED On, 0 for LED Off: ')
if KBInput == '1':
GPIO.output(LEDPin,GPIO.HIGH)
print('LED On ')
if KBInput == '0':
GPIO.output(LEDPin,GPIO.LOW)
print('LED Off ')
try:
main()
except KeyboardInterrupt:
print('\n\nGoodbye')
GPIO.output(LEDPin,GPIO.LOW)
GPIO.cleanup()
1 Answer 1
I have figured it out. For some reason in the IDE the keyboard input is received as a string, where as in the terminal it is received as an int. So i just needed to make the line like the following to work on both. It will also work through Putty.
if KBInput == '1' or KBInput == 1:
-
This means, you used Python 2 in the Terminal. Thonny uses Python 3.Aivar– Aivar2018年03月18日 15:00:19 +00:00Commented Mar 18, 2018 at 15:00
-
Is there a way to make sure it uses Python 3 in the terminal?dka13– dka132018年03月18日 17:35:22 +00:00Commented Mar 18, 2018 at 17:35
-
2How did you run the code in the terminal? The command
python
uses Python 2 andpython3
uses Python 3.Aivar– Aivar2018年03月18日 17:54:22 +00:00Commented Mar 18, 2018 at 17:54 -
Turned out @aivar's comment was the solution to my issue similar to the OPfrostshoxx– frostshoxx2019年11月14日 04:22:15 +00:00Commented Nov 14, 2019 at 4:22