我是新手程序员。我学会了在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
答案 0 :(得分:0)
我没有使用Python进行Pi编码,但我对该语言非常熟悉。这是一个快速鼓动的例子,可以清理你的代码,并为你提供所需的动作;引脚将保持在它的最后状态,直到第二次被选中,这将把它切换到它的相反状态。
我们只是将所有引脚映射到字典中的选择号,而不是使用一堆if/else
语句,并将用户的选择作为返回的关键字输入dict BCM引脚号并直接对其进行操作。您几乎肯定想要添加进一步的错误检查(例如,如果用户发送了alpha char):
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pins = {
1: 9,
2: 10,
3: 22,
4: 27,
5: 17,
6: 4,
7: 3,
8: 2
}
for pin in pins.values():
GPIO.setup(pin, GPIO.OUT)
while True:
choice = int(input("\nenter a pin number (0 to exit): "))
if choice == 0:
exit()
if choice not in pins.keys():
print("\ninvalid selection...\n")
continue
pin = pins[choice]
print("working on pin {}\n".format(pin))
GPIO.output(pin, not GPIO.input(pin))
print("pin {}: status {}\n".format(pin, GPIO.input(pin)))
GPIO.cleanup()