Skip to content

unit ButtonT

em.utils/ButtonT.em
package em.utils

template ButtonT

end

def em$generateUnit(pn, un)
|->>>
    ## ---- generated by em.utils/ButtonT ---- ##
    package `pn`

    from em.hal import ButtonI
    from em.hal import GpioEdgeDetectMinI

    from em.mcu import Poller

    from em.utils import FiberMgr

    module `un`: ButtonI
        #   ^| implements the ButtonI interface
        proxy Edge: GpioEdgeDetectMinI
        #   ^| a GPIO with edge-detection capabilities
    private:

        function buttonHandler: Edge.Handler
        function debounceFB: FiberMgr.FiberBodyFxn

        config debounceF: FiberMgr.Fiber&

        var curDuration: uint16
        var curCb: OnPressedCB
        var maxDur: uint16
        var minDur: uint16

    end

    def em$construct()
        Edge.setDetectHandlerH(buttonHandler)
        debounceF = FiberMgr.createH(debounceFB)
    end 

    def em$startup()
        Edge.makeInput()
        Edge.setInternalPullup(true)
        Edge.setDetectFallingEdge()
    end

    def buttonHandler()
        Edge.clearDetect()
        debounceF.post() if curCb
    end

    def debounceFB(arg)
        curDuration = 0
        for ;;
            Poller.pause(minDur)
            return if curDuration == 0 && !isPressed()
            curDuration += minDur
            break if !isPressed() || curDuration >= maxDur
        end
        curCb()
    end

    def isPressed()
        return !Edge.get()
    end

    def onPressed(cb, minDurationMs, maxDurationMs)
        curCb = cb
        maxDur = maxDurationMs
        minDur = minDurationMs
        if cb == null
            Edge.disableDetect()
        else
            Edge.enableDetect()
        end
    end
|-<<<
end