//ArduinoIDEにコピーして使います。 by Paradise
- #include <Wire.h> //Include the Wire.h library so we can communicate with the Nunchuck
- #define I2C_SDA 21 // Nuncuck SDA input ESP32=21 C3=8
- #define I2C_CLK 22 // Nuncuck CLK input ESP32=22 C3=9
- uint8_t nunbuff[12];
- int cnt = 0;
- int x_val = 0; // 1byte Data
- int y_val = 0; // 1byte Data
- int z_val = 0; // 1byte Data
- void setup () {
- Serial.begin (115200);
- Wire.begin();
- nunchuck_init();
- }
- void nunchuck_init() {
- Wire.beginTransmission(0x52); // transmit to device 0x52
- Wire.write(0x40); // sends memory address *(blackNunchuck:0xF0)
- Wire.write(0x00); // sends sent a zero. *(blackNunchuck:0x55)
- Wire.endTransmission(); // stop transmitting
- }
- void send_zero() {
- Wire.beginTransmission(0x52); // transmit to device 0x52
- Wire.write(0x00); // sends one byte
- Wire.endTransmission(); // stop transmitting
- }
- void loop () {
- Wire.requestFrom(0x52, 6); // request data from nunchuck
- while (Wire.available()) {
- nunbuff[cnt] = nunchuk_decode_byte(Wire.read());
- cnt++;
- }
- int z = 0;
- int c = 0;
- if (cnt >= 5) {
- x_val = nunbuff[0];
- y_val = nunbuff[1];
- x_val = x_val + 4; //最初に誤差補正をして置くこと
- y_val = y_val - 6; //最初に誤差補正をして置くこと
- Serial.print(" x_val = ");
- Serial.print(x_val);
- Serial.print(" y_val = ");
- Serial.print(y_val);
- Serial.print(" z_val = ");
- Serial.println(z_val);
- if ((nunbuff[5] >> 0) & 1) z = 1; // The first bit of data of the 5byte (Nuncuck Z-button)
- if ((nunbuff[5] >> 1) & 1) c = 1; // The second bit of data of the 5byte (Nuncuck C-button)
- if ((z == 1) & (c == 1)) z_val = 0;
- if ((z == 0) & (c == 1)) z_val = 1;
- if ((z == 1) & (c == 0)) z_val = 2;
- if ((z == 0) & (c == 0)) z_val = 3;
- delay(1);
- }
- cnt = 0;
- send_zero(); // send the request for next bytes
- delay(10);
- }
- char nunchuk_decode_byte (char x) {
- x = (x ^ 0x17) + 0x17;
- return x;
- }