Shop OBEX P1 Docs P2 Docs Learn Events
Background button monitor -- no extra cog — Parallax Forums

Background button monitor -- no extra cog

Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
edited 2022-01-27 22:01 in PASM/Spin (P1)

For a device I'm working on, I needed a way to monitor a push-button for several different durations of push:

  1. At least 1/100 sec. as a selector within an operating mode,
  2. At least 1 sec to change operating modes.
  3. Five seconds or more to reboot.

I didn't want to start a new cog to do this and decided one of the counters could do the background button monitoring for me. Here's what I came up with:

PUB start

  ctra := %01100 << 26 | BTN_PIN   'Set up CTRA to measure the time the button input is low.
  frqa := 1
  btn_min := clkfreq / 100  'Time for a simple button press.
  btn_max := clkfreq        'Time for a mode change
  btn_reset := clkfreq * 5  'Time for a reboot.
  ...

PUB button_pushed | count

  if ((count := phsa) => btn_min and ina[BTN_PIN])   'Proceed if button was pressed long enough and now released.
    waitcnt(cnt + clkfreq / 100)   'Delay for debouncing.
    phsa~   'Clear the counter.
    return count   'Return the duration of the button press.
  'Otherwise return 0.

It seems to work!

-Phil

Comments

  • evanhevanh Posts: 15,848
    edited 2022-01-27 20:47

    Add comment about the IF triggering on button release. Quicker to grok then.

    PS: Looks solid really. Good piece of code.

  • The IF checks to see if the button was pressed for the minimum amount of time required and if the button has been released. If both conditions have not been met, it returns zero.

    BTW, the waitcnt is to ensure debouncing.

    -Phil

Sign In or Register to comment.