2

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()
asked Mar 18, 2018 at 2:00
0

1 Answer 1

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:

answered Mar 18, 2018 at 4:47
4
  • This means, you used Python 2 in the Terminal. Thonny uses Python 3. Commented Mar 18, 2018 at 15:00
  • Is there a way to make sure it uses Python 3 in the terminal? Commented Mar 18, 2018 at 17:35
  • 2
    How did you run the code in the terminal? The command python uses Python 2 and python3 uses Python 3. Commented Mar 18, 2018 at 17:54
  • Turned out @aivar's comment was the solution to my issue similar to the OP Commented Nov 14, 2019 at 4:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.