我为学校作业写了一段代码:
写入一个功能,通过按下输入开关来改变LED的亮度(pwm)。第一次按住可以增加亮度,下一次按下会降低亮度。
它在0到100之间时有效,但当它达到0或100时它就会停止工作。这是代码:
import RPi.GPIO as GPIO
def main():
sw = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(sw, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(2, GPIO.OUT)
pwm_red=GPIO.PWM(2,500)
pwm_red.start(100)
bright=0
state=0
while 1:
if swin=GPIO.input(sw)
if state== 1 and bright !=100: '''I put bright !=100 becuase without it, it would just kick me out of the loop when hits 100'''
bright=bright+1
pwm_red.ChangeDutyCycle(bright)
print(bright)
while GPIO.input(sw)==1:
state=0
if state ==0 and bright !=0:
bright=bright-1
pwm_red.ChangeDutyCycle(bright)
print(bright)
while GPIO.input(sw)==1:
state=1
有人可以帮我找到解决方案吗?我制作了这个代码的多个版本,他们都有这个问题。我试图谷歌问题,但那里什么都没有。我可以做到它从来没有达到100也不是0,但它不是正确的解决方案。我希望它被关闭(当它仍然是99.999999时)
答案 0 :(得分:0)
说实话,我很惊讶目前的编码工作正常。我会在这里更改逻辑,在事件循环中第一个if之后立即检查按钮状态。
尝试类似以下内容,我尚未测试
import RPi.GPIO as GPIO
from time import sleep
def main():
sw = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(sw, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(2, GPIO.OUT)
pwm_red=GPIO.PWM(2, 50) # 50 Hz should be fine
bright=100
pwm_red.start(bright)
state=-1
while True:
while GPIO.input(sw)
while GPIO.input(sw) and (0 <= bright + state <= 100):
bright += state
pwm_red.ChangeDutyCycle(bright)
print(bright)
sleep(0.1)
sleep(0.1)
state *= -1
# Avoid excessive polling
while not GPIO.input(sw):
sleep(0.1)
答案 1 :(得分:0)
def main2():
sw=17
GPIO.setmode(GPIO.BCM)
GPIO.setup(sw, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setwarnings(False)
GPIO.setup(2, GPIO.OUT)
pwm_red = GPIO.PWM(2, 50)
pwm_red.start(100)
bright=100
state=-1
while True:
swin=GPIO.input(sw)
while swin == False:
if state == 1 and bright !=100:
bright+=5
pwm_red.ChangeDutyCycle(bright)
print(bright)
while GPIO.input(sw)==1:
state *= -1
time.sleep(0.1)
if bright == 100:
state *=-1
time.sleep(0.3)
if bright == 0:
state *=-1
time.sleep(0.3)
if state == -1 and bright !=0:
bright-=5
pwm_red.ChangeDutyCycle(bright)
print(bright)
while GPIO.input(sw)==1:
state *= -1
time.sleep(0.1)