Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Streaming.h>
- #include <Wire.h>
- #define NUNCHUK_ADDRESS 0x52
- #define NUNCHUK_DATA_LENGTH 6
- #define JOY_X_CENTER 123
- #define JOY_Y_CENTER 129
- uint8_t nunchuk_buffer[NUNCHUK_DATA_LENGTH];
- uint8_t nunchuk_buffer_count;
- void nunchuk_init()
- {
- Wire.beginTransmission(NUNCHUK_ADDRESS);
- Wire.write(0xF0);
- Wire.write(0x55);
- Wire.endTransmission();
- Wire.beginTransmission(NUNCHUK_ADDRESS);
- Wire.write(0xFB);
- Wire.write(0x00);
- Wire.endTransmission();
- }
- void nunchuk_request_data()
- {
- Wire.beginTransmission(NUNCHUK_ADDRESS);
- Wire.write(0x00);
- Wire.endTransmission();
- }
- uint8_t nunchuk_read()
- {
- Wire.requestFrom(NUNCHUK_ADDRESS, NUNCHUK_DATA_LENGTH);
- nunchuk_buffer_count = 0;
- while(Wire.available())
- {
- nunchuk_buffer[nunchuk_buffer_count] = Wire.read();
- nunchuk_buffer_count++;
- }
- if (nunchuk_buffer_count > 5)
- {
- nunchuk_request_data();
- }
- return nunchuk_buffer_count;
- }
- inline uint8_t nunchuk_joyX()
- {
- return nunchuk_buffer[0];
- }
- inline uint8_t nunchuk_joyY()
- {
- return nunchuk_buffer[1];
- }
- inline uint8_t nunchuk_buttonZ()
- {
- return !(nunchuk_buffer[5] & 0b1);
- }
- inline uint8_t nunchuk_buttonC()
- {
- return !(nunchuk_buffer[5] & 0b10);
- }
- inline int nunchuk_aX()
- {
- return (((nunchuk_buffer[5]>>2) & 0b11) | ((int)nunchuk_buffer[2])<<2);
- }
- inline int nunchuk_aY()
- {
- return (((nunchuk_buffer[5]>>4) & 0b11) | ((int)nunchuk_buffer[3])<<2);
- }
- inline int nunchuk_aZ()
- {
- return (((nunchuk_buffer[5]>>6) & 0b11) | ((int)nunchuk_buffer[4])<<2);
- }
- inline double nunchuk_joyAng()
- {
- return atan2(nunchuk_joyY(), nunchuk_joyX());
- }
- inline double nunchuk_joyMag()
- {
- double x = (double)(nunchuk_joyX() - JOY_X_CENTER)/125.0;
- double y = (double)(nunchuk_joyY() - JOY_Y_CENTER)/125.0;
- return sqrt(x*x + y*y);
- }
- void print_nunchuk_data()
- {
- Serial<<"Acc X: "<< nunchuk_aX() << " Acc X: " << nunchuk_aY() << " Acc Z: " << nunchuk_aZ() << endl;
- Serial<<"Joy X: "<< nunchuk_joyX() << " Joy y: " << nunchuk_joyY() << endl;
- Serial<<"Button C: "<< nunchuk_buttonC() << " Button Z: " << nunchuk_buttonZ() << endl<<endl;
- }
- void setup()
- {
- Serial.begin(9600);
- Wire.begin();
- nunchuk_init();
- Serial.println("Inited");
- }
- void loop()
- {
- nunchuk_read();
- print_nunchuk_data();
- delay(500);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement