kjohns kjohns - 1 year ago 50
Python Question

Qt Creator incremental step versus "for in range" loop

I have Qt Creator buttons that control a digital potentiometer (connected to an LED at the moment). The way the code is written right now, the "increase" button takes the LED from full dim and incrementally steps it up to full bright and likewise the "decrease" button does the opposite. This is working just fine but what I am wanting is for each button press to increase or decrease the led brightness one step per push, rather than full dim to bright, or bright to dim, if that makes sense. Here's what I have now:

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)


So with each button press I would like the resistance value of the digital pot to increase or decrease by "5" and not go through the entire range. So it's partially working but I'm stuck at this point. Thanks for any help.

Answer Source

It seems that your LED controller always take a full brightness value (with a static command 0x11 in the higher 8 bits) so you need to store its state somewhere outside of your methods for persistence.

edit: here's how it could behave in a class. It's also optimized so it doesn't make unnecessary calls to your controller plus you can use o2dim() to dim up/down your light in arbitrary increments.

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download