Advertisement
Guest User

cusao

a guest
Mar 4th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. #include <Wire.h>
  2. #define nunchuk_ID 0xA4 >> 1
  3.  
  4. unsigned char buffer[6];
  5. int cnt = 0;
  6.  
  7. void setup ()
  8. {
  9. Serial.begin (9600);
  10. Wire.begin ();
  11. nunchuck_init ();
  12. delay (100);
  13. }
  14.  
  15. void nunchuck_init ()
  16. {
  17. Wire.beginTransmission (nunchuk_ID);
  18. Wire.write (0x40);
  19. Wire.write (0x00);
  20. Wire.endTransmission ();
  21. }
  22. void send_zero ()
  23. {
  24. Wire.beginTransmission (nunchuk_ID);
  25. Wire.write (0x00);
  26. Wire.endTransmission ();
  27. }
  28. void loop ()
  29. {
  30. Wire.requestFrom (nunchuk_ID, 6);
  31. while (Wire.available ())
  32. {
  33. buffer[cnt] = nunchuk_decode_byte (Wire.read ());
  34. cnt++;
  35. }
  36.  
  37. if (cnt >= 5)
  38. {
  39. print ();
  40. }
  41. cnt = 0;
  42. send_zero ();
  43. delay (100);
  44. }
  45.  
  46. void print ()
  47. {
  48. unsigned char joy_x_axis;
  49. unsigned char joy_y_axis;
  50. int accel_x_axis;
  51. int accel_y_axis;
  52. int accel_z_axis;
  53. unsigned char z_button;
  54. unsigned char c_button;
  55. joy_x_axis = buffer[0];
  56. joy_y_axis = buffer[1];
  57. accel_x_axis = (buffer[2]) << 2;
  58. accel_y_axis = (buffer[3]) << 2;
  59. accel_z_axis = (buffer[4]) << 2;
  60.  
  61. if ((buffer[5] & 0x01)!=0)
  62. { z_button = 1; }
  63. else
  64. { z_button = 0; }
  65. if ((buffer[5] & 0x02)!=0)
  66. { c_button = 1; }
  67. else
  68. { c_button = 0; }
  69. accel_x_axis += ((buffer[5]) >> 2) & 0x03;
  70. accel_y_axis += ((buffer[5]) >> 4) & 0x03;
  71. accel_z_axis += ((buffer[5]) >> 6) & 0x03;
  72. Serial.print (joy_x_axis, DEC);
  73. Serial.print ("\t");
  74. Serial.print (joy_y_axis, DEC);
  75. Serial.print ("\t");
  76. Serial.print (accel_x_axis, DEC);
  77. Serial.print ("\t");
  78. Serial.print (accel_y_axis, DEC);
  79. Serial.print ("\t");
  80. Serial.print (accel_z_axis, DEC);
  81. Serial.print ("\t");
  82. Serial.print (z_button, DEC);
  83. Serial.print ("\t");
  84. Serial.print (c_button, DEC);
  85. Serial.print ("\r\n");
  86. }
  87.  
  88. char nunchuk_decode_byte (char x)
  89. {
  90. x = (x ^ 0x17) + 0x17;
  91. return x;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement