/ examples / nunchuk_accel_mouse.py
nunchuk_accel_mouse.py
 1  import board
 2  import adafruit_nunchuk
 3  from adafruit_hid.mouse import Mouse
 4  
 5  m = Mouse()
 6  nc = adafruit_nunchuk.Nunchuk(board.I2C())
 7  
 8  centerX = 120
 9  centerY = 110
10  
11  scaleX = 0.4
12  scaleY = 0.5
13  
14  cDown = False
15  zDown = False
16  
17  # This is to allow double checking (only on left click - and it doesn't really work)
18  CHECK_COUNT = 0
19  
20  
21  # This is just to show that we're getting back data - uncomment it and hold down the buttons
22  # while True:
23  #    print((0 if nc.button_C else 1, 0 if nc.button_Z else 1))
24  
25  while True:
26      accel = nc.acceleration
27      #    print(accel)
28      #    x, y = nc.joystick
29      #    print((x,y))
30      x = accel[0] / 4
31      y = accel[1] / 4
32      print((x, y))
33      # Eliminate spurious reads
34      if x == 255 or y == 255:
35          continue
36      relX = x - centerX
37      relY = y - centerY
38  
39      m.move(int(scaleX * relX), int(scaleY * relY), 0)
40  
41      c = nc.button_C
42      z = nc.button_Z
43  
44      if z and not zDown:
45          stillDown = True
46          for n in range(CHECK_COUNT):
47              if nc.button_Z:
48                  stillDown = False
49                  break
50          if stillDown:
51              m.press(Mouse.LEFT_BUTTON)
52              zDown = True
53      elif not z and zDown:
54          stillDown = True
55          for n in range(CHECK_COUNT):
56              if not nc.button_Z:
57                  stillDown = False
58                  break
59          if stillDown:
60              m.release(Mouse.LEFT_BUTTON)
61              zDown = False
62      if c and not cDown:
63          m.press(Mouse.RIGHT_BUTTON)
64          cDown = True
65      elif not c and cDown:
66          m.release(Mouse.RIGHT_BUTTON)
67          cDown = False