Skip to content

Instantly share code, notes, and snippets.

@randrews
Created May 30, 2021 21:29
Show Gist options
  • Save randrews/a41e937076bc6a8c0df7f7056a0654dd to your computer and use it in GitHub Desktop.
Save randrews/a41e937076bc6a8c0df7f7056a0654dd to your computer and use it in GitHub Desktop.
-- Set up an i2c interface. Using a hardware one, on "slow" speed.
-- If it works on slow it should work period.
local iface = i2c.HW0
i2c.setup(iface, 21, 22, i2c.SLOW)
-- Ask the IO expander what's up:
function query()
i2c.start(iface) -- Start a frame
i2c.address(iface, 0x20, i2c.RECEIVER) -- We're reading from 0x20
i2c.read(iface, 1) -- Read one byte
i2c.stop(iface) -- Close the frame
-- All this just queued instructions to the HW interface. This is
-- what actually runs it and calls the callback when it's done
i2c.transfer(iface, query_cb)
end
local bounce = false -- Are we just waiting for the bounce to stop?
-- Callback for asking an IO expander what's up
function query_cb(value, ack)
if ack then -- If the device didn't work, then skip it.
local flags = value:byte() % 4 -- Pull the low two bits off the register
if not bounce then -- Ignore changes past the first one
if flags == 1 then print('ccw') -- Low bit falling first means we turned ccw
elseif flags == 2 then print('cw') end -- High bit is a cw turn
-- Either way, after this some more stuff will happen: the other line will
-- fall, then they'll both go back up and fall a few more times, because
-- switches bounce. Ignore all the changes until it settles to them both
-- high again:
bounce = true
elseif flags == 3 then -- Both switches have returned back to high
bounce = false -- So all bouncing is over until next time
print('-----')
end
end
end
-- Enable the pullup resistor on the pin we're using for interrupt input
gpio.config { gpio = 26, dir = gpio.IN, pull = gpio.PULL_UP }
-- And call query() when the interrupt falls
gpio.trig(26, gpio.INTR_DOWN, query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment