Sparkfun's Qwiic joystick and keypad

This commit is contained in:
James Bowman 2019-03-03 17:49:22 -08:00
parent cb681cfebe
commit 6885c0b9fe
2 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,43 @@
"""
Example for Qwiic Joystick
Available from Sparkfun.
"""
import sys
import time
import struct
from i2cdriver import I2CDriver
class Joystick:
def __init__(self, i2, a = 0x20):
self.i2 = i2
self.a = a
def axis(self, i):
self.i2.start(self.a, 0)
self.i2.write([i])
self.i2.stop() # Note: their firmware cannot handle an I2C restart
self.i2.start(self.a, 1)
(r,) = struct.unpack(">H", self.i2.read(2))
self.i2.stop()
return r
def read(self):
"""
return the joystick (x,y) position. The range is 0-1023.
The center position of the joystick is approximately 512.
"""
# Note: their firmware requires two separate reads
return (self.axis(0), self.axis(2))
if __name__ == '__main__':
i2 = I2CDriver(sys.argv[1])
d = Joystick(i2)
while 1:
print(d.read())
time.sleep(.1)

View File

@ -0,0 +1,44 @@
"""
Example for Qwiic Keypad
Available from Sparkfun.
"""
import sys
import time
import struct
from i2cdriver import I2CDriver
class Keypad:
def __init__(self, i2, a = 0x4b):
self.i2 = i2
self.a = a
def read_ts(self):
"""
Return (key, timestamp) if pressed, or None.
"""
self.i2.start(self.a, 1)
(k, age_in_ms) = struct.unpack(">BH", self.i2.read(3))
self.i2.stop()
if k != 0:
return (chr(k), time.time() - age_in_ms * .001)
else:
return None
def read(self):
r = self.read_ts()
if r:
return r[0]
else:
return None
if __name__ == '__main__':
i2 = I2CDriver(sys.argv[1])
d = Keypad(i2)
while 1:
print(d.read())
time.sleep(.1)