errorflash
Posts: 1
Joined: Sat Jul 24, 2021 6:55 pm

Toggle Switch Read Out

Sat Jul 24, 2021 7:03 pm

Hello

I came from Arduino programming and have no high IQ in MicroPython.

I need a code that read the Status from a toggle switch. The code must read the only status change. When i Switch On the pi must send a "1" at GP0 and when i switch off GP1 must send a "1" only one times for 1 Second and every time at status change.

Thanks for Help!

danjperron
Posts: 3840
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: Toggle Switch Read Out

Mon Jul 26, 2021 5:36 pm

Code: Select all

from machine import Pin
import utime

class Debounce:
    def __init__(self,pin,debounceTimems=10):
        self.pin = pin
        self.pinValue = self.pin.value()
        self.utimems = utime.ticks_ms()
        self.debounceTimems = debounceTimems
        
    def isChanged(self):
        pinValue = self.pin.value()
        if pinValue is not self.pinValue:
            if (utime.ticks_ms()-self.utimems) > self.debounceTimems:
                self.pinValue= pinValue
                return True, pinValue
        else:
            self.utimems= utime.ticks_ms()
        return False, pinValue
            
if __name__ == "__main__":
    debouncePin = Debounce(Pin(19,Pin.IN,Pin.PULL_UP))
    
while True:
    flag, pinValue = debouncePin.isChanged()
    if flag:
        print(pinValue)
    utime.sleep_ms(1)
    
        
When i Switch On the pi must send a "1" at GP0 and when i switch off GP1 must send a "1" only one times for 1 Second and every time at status change.
Can't figure out what you mean! The code I send you only send the status when the switch changes. I include a debounce timeout of 10 ms. Do you mean that if the switch is toggle in less than 1 second the status is not send. If it is then the debounce should be 1 second.

Return to “MicroPython”