forked from caternuson/CircuitPython_Nunchuk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnunchuk.py
More file actions
79 lines (70 loc) · 2.76 KB
/
nunchuk.py
File metadata and controls
79 lines (70 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# The MIT License (MIT)
#
# Copyright (c) 2019 Carter Nelson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time
from adafruit_bus_device.i2c_device import I2CDevice
_DEFAULT_ADDRESS = 0x52
_I2C_INIT_DELAY = .1
_I2C_READ_DELAY = 0.01
class Nunchuk:
"""Class which provides interface to Nintendo Nunchuk controller."""
def __init__(self, i2c, address=_DEFAULT_ADDRESS):
self.buffer = bytearray(6)
self.i2c_device = I2CDevice(i2c, address)
time.sleep(_I2C_INIT_DELAY)
with self.i2c_device as i2c:
# turn off encrypted data
# http://wiibrew.org/wiki/Wiimote/Extension_Controllers
i2c.write(b'\xF0\x55')
time.sleep(_I2C_INIT_DELAY)
i2c.write(b'\xFB\x00')
self._read_data()
@property
def joystick(self):
self._read_data()
return self.buffer[0], self.buffer[1]
@property
def button_C(self):
return not bool(self._read_data()[5] & 0x02)
@property
def button_Z(self):
return not bool(self._read_data()[5] & 0x01)
@property
def acceleration(self):
self._read_data()
x = (self.buffer[5] & 0xC0) >> 6
x |= self.buffer[2] << 2
y = (self.buffer[5] & 0x30) >> 4
y |= self.buffer[3] << 2
z = (self.buffer[5] & 0x0C) >> 2
z |= self.buffer[4] << 2
return x, y, z
def _read_data(self):
return self._read_register(b'\x00')
def _read_register(self, address):
with self.i2c_device as i2c:
time.sleep(_I2C_READ_DELAY)
# i2c.write_then_readinto(address, self.buffer)
i2c.write(address)
time.sleep(_I2C_READ_DELAY)
i2c.readinto(self.buffer)
time.sleep(_I2C_READ_DELAY)
return self.buffer