【发布时间】:2017-05-13 20:31:20
【问题描述】:
我是一个新手程序员。我在 Commodore 64 天学会了 Basic 编码。最近,我购买了一个 Raspberry Pi 3 和一个 8 通道继电器板,并正在用 Python 3.x 编写一个脚本来通过 GPIO 引脚控制继电器板。我编写的脚本有效,但我怀疑它不是很有效。任何批评或建议将不胜感激。
话虽如此,我想更改脚本以在输入数字时切换引脚的状态。目前,当用户输入一个数字时,该引脚会激活几秒钟然后关闭。我希望引脚保持活动状态,直到用户再次选择相同的数字。我相当肯定我可以编写一些可行的代码,但是,我最初的想法是启动另一个循环,将其再次关闭。不确定这是否有意义,但我确信这不是一个优雅或高效编码的解决方案。
任何建议或帮助将不胜感激。
import RPi.GPIO as GPIO # import the GPIO Library
import time # import system time
GPIO.setmode(GPIO.BCM) # set pin numbering
PinList = [2, 3, 4, 17, 27, 22, 10, 9] # init list with pin numbers
SleepTime = 4 # set sleep delay variable
for i in PinList: # loop through pins and set mode and state to 'low'
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# Get user input, turn on the appropriate GPIO pin, pause, then turn it off.
while True:
choice = input("\nEnter a number between 1 and 8.\nEnter 0 to exit: ")
if choice == '0':
break
if choice == '1':
print("You chose 1")
GPIO.output(9, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(9, GPIO.HIGH)
elif choice == '2':
print("You chose 2")
GPIO.output(10, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(10, GPIO.HIGH)
elif choice == '3':
print("You chose 3")
GPIO.output(22, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(22, GPIO.HIGH)
elif choice == '4':
print("You chose 4")
GPIO.output(27, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(27, GPIO.HIGH)
elif choice == '5':
print("You chose 5")
GPIO.output(17, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(17, GPIO.HIGH)
elif choice == '6':
print("You chose 6")
GPIO.output(4, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(4, GPIO.HIGH)
elif choice == '7':
print("You chose 7")
GPIO.output(3, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(3, GPIO.HIGH)
elif choice == '8':
print("You chose 8")
GPIO.output(2, GPIO.LOW)
time.sleep(SleepTime)
GPIO.output(2, GPIO.HIGH)
else:
print("\nThat is not a valid input.")
print ("\n Quit")
GPIO.cleanup() # Reset GPIO pin settings
【问题讨论】:
标签: python python-3.x raspberry-pi raspberry-pi3