我有Qt Creator按钮,可以控制数字电位器(目前连接到LED(。 现在编写代码的方式是,"增加"按钮将LED从全暗中取出,并逐步将其提升到全亮,同样,"减少"按钮的作用恰恰相反。 这工作得很好,但我想要的是每次按下按钮每次按一下都增加或减少 LED 亮度一步,而不是完全调暗到亮,或者亮到暗,如果这有意义的话。 这是我现在拥有的:
def o2zeroup(self):
for resist_val in range(64, 1, -5):
cmd = int("00010001", 2)
cmd <<= 8
digipot1.put(cmd|resist_val, bits=64)
time.sleep(0.3)
def o2zerodown(self):
for resist_val in range(-1, 64, 5):
cmd = int("00010001", 2)
cmd <<= 8
digipot1.put(cmd|resist_val, bits=64)
time.sleep(0.3)
因此,每次按下按钮,我希望数字电位器的电阻值增加或减少"5",而不是在整个范围内。 所以它部分有效,但我被困在这一点上。 感谢您的任何帮助。
似乎您的 LED 控制器始终采用完整的亮度值(静态命令0x11
较高的 8 位(,因此您需要将其状态存储在方法之外的某个位置以实现持久性。
编辑:这是它在课堂上的行为方式。它还经过优化,因此不会对您的控制器进行不必要的调用,而且您可以使用o2dim()
以任意增量调暗/调暗灯光。
def __init__(self): # the signature could be different
# your code...
self.resist_val = 0 # default (init) state
self.dim_step = 5 # how much to increase/decrease on each call
self.dim_command = 0x11 << 8 # change brightness command
# call this only if your global digipot1 variable is initialized:
self.o2dim(64) # initialize the default state to 64
# rest of your class code
def o2dim(self, change=0): # update the current dim state
value = max(-1, min(64, self.resist_val + change)) # limit the state between -1 and 64
if value != self.resist_val: # update only if changed
digipot1.put(self.dim_command | value, bits=64)
self.resist_val = value
def o2zeroup(self):
self.o2dim(-self.dim_step)
def o2zerodown(self):
self.o2dim(self.dim_step)