//ArduinoIDEにコピーして使います。 by Paradise
  1. #include <Wire.h> //Include the Wire.h library so we can communicate with the Nunchuck
  2. #define I2C_SDA 21 // Nuncuck SDA input ESP32=21 C3=8
  3. #define I2C_CLK 22 // Nuncuck CLK input ESP32=22 C3=9
  4. uint8_t nunbuff[12];
  5. int cnt = 0;
  6. int x_val = 0; // 1byte Data
  7. int y_val = 0; // 1byte Data
  8. int z_val = 0; // 1byte Data
  9. void setup () {
  10.   Serial.begin (115200);
  11.   Wire.begin();
  12.   nunchuck_init();
  13. }
  14. void nunchuck_init() {
  15.   Wire.beginTransmission(0x52); // transmit to device 0x52
  16.   Wire.write(0x40); // sends memory address *(blackNunchuck:0xF0)
  17.   Wire.write(0x00); // sends sent a zero. *(blackNunchuck:0x55)
  18.   Wire.endTransmission(); // stop transmitting
  19. }
  20. void send_zero() {
  21.   Wire.beginTransmission(0x52); // transmit to device 0x52
  22.   Wire.write(0x00); // sends one byte
  23.   Wire.endTransmission(); // stop transmitting
  24. }
  25. void loop () {
  26.   Wire.requestFrom(0x52, 6); // request data from nunchuck
  27.   while (Wire.available()) {
  28.     nunbuff[cnt] = nunchuk_decode_byte(Wire.read());
  29.     cnt++;
  30.   }
  31.   int z = 0;
  32.   int c = 0;
  33.   if (cnt >= 5) {
  34.     x_val = nunbuff[0];
  35.     y_val = nunbuff[1];
  36.     x_val = x_val + 4; //最初に誤差補正をして置くこと
  37.     y_val = y_val - 6; //最初に誤差補正をして置くこと
  38.     Serial.print(" x_val = ");
  39.     Serial.print(x_val);
  40.     Serial.print(" y_val = ");
  41.     Serial.print(y_val);
  42.     Serial.print(" z_val = ");
  43.     Serial.println(z_val);
  44.     if ((nunbuff[5] >> 0) & 1) z = 1; // The first bit of data of the 5byte (Nuncuck Z-button)
  45.     if ((nunbuff[5] >> 1) & 1) c = 1; // The second bit of data of the 5byte (Nuncuck C-button)
  46.     if ((z == 1) & (c == 1)) z_val = 0;
  47.     if ((z == 0) & (c == 1)) z_val = 1;
  48.     if ((z == 1) & (c == 0)) z_val = 2;
  49.     if ((z == 0) & (c == 0)) z_val = 3;
  50.     delay(1);
  51.   }
  52.   cnt = 0;
  53.   send_zero(); // send the request for next bytes
  54.   delay(10);
  55. }
  56. char nunchuk_decode_byte (char x) {
  57.   x = (x ^ 0x17) + 0x17;
  58.   return x;
  59. }