gpt4 book ai didi

python - 使用 MCP3002 模数转换器控制 LED 亮度

转载 作者:行者123 更新时间:2023-12-05 07:10:44 28 4
gpt4 key购买 nike

我正在尝试使用 MCP3002 ADC 和电位计来控制 PWMLED 亮度列表。

我的问题是,当我运行我的脚本时,除了连接到 MCP3002 ADC 的电位器之外,一切都按预期运行,它不会在我调整旋钮时调整我的 PWMLED 的亮度。

这是我的代码:

#!/usr/bin/python3

from gpiozero import PWMLED, Button, MCP3002
from threading import Thread
from signal import pause
from time import sleep
LEDs = [PWMLED(5), PWMLED(17), PWMLED(22), PWMLED(19), PWMLED(26)]
potentiometer = MCP3002(0)
pushButton = Button(21)
SPEED = 0.03


def analogRead(): # Now this function is working
while True: # the potentiometer value gets
global LEDs # displayed on the screen and it changes as
print("analogRead called") # I adjust the knob but the ledSequnce() lights keep
for PWMLED in LEDs: # flickering, and the sequence gets interrupted
if potentiometer.value < 0.02:
PWMLED.value = 0
else:
PWMLED.value = potentiometer.value
print(potentiometer.value)
sleep(0.1)


def speedCounter():
global SPEED
if SPEED < 0.4:
SPEED += 0.1
else:
SPEED = 0.03


def ledSequence():
while True:
for PWMLED in LEDs:
PWMLED.on()
sleep(SPEED)
PWMLED.off()
for PWMLED in reversed(LEDs):
PWMLED.on()
sleep(SPEED)
PWMLED.off()


try:
pushButton.when_pressed = speedCounter
ledFlash = Thread(target=ledSequence, daemon=True)
ledFlash.start()
pot = Thread(target=analogRead, daemon=True)
pot.start()
pause()

except KeyboardInterrupt:
exit(1)

但是当我尝试这个脚本时它工作得很好:

#!/usr/bin/python3

from gpiozero import PWMLED, MCP3002
from time import sleep

pot = MCP3002(0)
led = [PWMLED(5), PWMLED(17), PWMLED(22), PWMLED(19), PWMLED(26)]
while True:
for PWMLED in led:
if pot.value < 0.02:
PWMLED.value = 0
else:
PWMLED.value = pot.value

print(pot.value)
sleep(0.1)

非常感谢您的帮助!

最佳答案

我找到了解决问题的方法。所以,我想我应该把它贴在这里!

#!/usr/bin/python3

from gpiozero import PWMLED, Button, MCP3002
from threading import Thread
from signal import pause
from time import sleep
LEDs = [PWMLED(5), PWMLED(17), PWMLED(22), PWMLED(19), PWMLED(26)]
potentiometer = MCP3002(0)
pushButton = Button(21)
SPEED = 0.03


def speedCounter():
global SPEED
if SPEED < 0.4:
SPEED += 0.1
else:
SPEED = 0.03


def ledSequence():
while True:
for PWMLED in LEDs:
PWMLED.on()
PWMLED.value = potentiometer.value
sleep(SPEED)
PWMLED.off()
for PWMLED in reversed(LEDs):
PWMLED.on()
PWMLED.value = potentiometer.value
sleep(SPEED)
PWMLED.off()


try:
pushButton.when_pressed = speedCounter
ledFlash = Thread(target=ledSequence, daemon=True)
ledFlash.start()
pause()

except KeyboardInterrupt:
exit(1)

关于python - 使用 MCP3002 模数转换器控制 LED 亮度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61106506/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com