#define WII_IDENT_LEN ((byte)6)
#define WII_TELEGRAM_LEN ((byte)6)
#define WII_NUNCHUCK_TWI_ADR ((byte)0x52)
#include <Wire.h>
#include <string.h>
#include <utility/twi.h>
#include <Servo.h> 
Servo myservo1;
Servo myservo2;
#undef int
#include <stdio.h>
uint8_t outbuf[WII_TELEGRAM_LEN];
int cnt = 0;
int ledPin = 13;
int servoPin1 = A0;
int servoPin2 = A1;
int adaptMinus = A2;
int adaptPlus = A3;
int z_button = 0;
int c_button = 0;
int locCx =   0;
int locCy =  79;
int locZx =  84;
int locZy =  97;
int servoPos1 = 90;
int servoPos2 = 90;
int pulseWidth = 0;
int pulseWidth2 = 0;
long lastPulse = 0;
long lastPulse2 = 0;
int refreshTime = 20;
int minPulse = 1000;
int minPulse2 = 500;
int dtime=10;
#define pwbuffsize 10
long pwbuff[pwbuffsize];
long pwbuffpos = 0;
long pwbuff2[pwbuffsize];
long pwbuffpos2 = 0;
boolean useAdapter = true;

void setup (){
  Serial.begin (115200);
  Wire.begin();
  #define TWI_FREQ_NUNCHUCK 400000L
  TWBR = ((CPU_FREQ / TWI_FREQ_NUNCHUCK) - 16) / 2;
  nunchuck_init(0);
  pinMode(ledPin, OUTPUT);      
  pinMode(servoPin1, OUTPUT);      
  pinMode(servoPin2, OUTPUT);
  if(useAdapter){
    pinMode(adaptMinus, OUTPUT);      
    pinMode(adaptPlus, OUTPUT);      
    digitalWrite (adaptMinus, LOW); // sets the -   for nunChuck
    digitalWrite (adaptPlus, HIGH); // sets the +    adapter
  }
  pulseWidth = minPulse;
  pulseWidth2 = minPulse2;
  byte i;
  if(readControllerIdent(outbuf) == 0){
    Serial.print("Ident=");
    for (i = 0; i < WII_TELEGRAM_LEN; i++){
      Serial.print(outbuf[i], HEX);
      Serial.print(' ');
    }
    Serial.println();
  }
  myservo1.attach(servoPin1);
  myservo2.attach(servoPin2);
  Serial.println("Finished setup");
}

byte nunchuck_init (unsigned short timeout){
  byte rc = 1;
  Wire.beginTransmission (WII_NUNCHUCK_TWI_ADR); // transmit to device 0x52
  Wire.send (0x40); // sends memory address
  Wire.send (0x00); // sends sent a zero.
  Wire.endTransmission (); // stop transmitting
  unsigned long time = millis();
  do{
    Wire.beginTransmission (WII_NUNCHUCK_TWI_ADR); // transmit to device 0x52
    Wire.send (0xF0); // sends memory address
    Wire.send (0x55); // sends data.
    if(Wire.endTransmission() == 0){ // stop transmitting
      Wire.beginTransmission (WII_NUNCHUCK_TWI_ADR); // transmit to device 0x52
      Wire.send (0xFB); // sends memory address
      Wire.send (0x00); // sends sent a zero.
      if(Wire.endTransmission () == 0){ // stop transmitting
        rc = 0;
      }
    }
  }
  while (rc != 0 && (!timeout || ((millis() - time) < timeout)));
  return rc;
}

byte readControllerIdent(byte* pIdent){
  byte rc = 1;
  Wire.beginTransmission (WII_NUNCHUCK_TWI_ADR); // transmit to device 0x52
  Wire.send (0xFA); // sends memory address of ident in controller
  if(Wire.endTransmission () == 0){ // stop transmitting
    byte i;
    Wire.requestFrom (WII_NUNCHUCK_TWI_ADR, WII_TELEGRAM_LEN); // request data from nunchuck
    for (i = 0; (i < WII_TELEGRAM_LEN) && Wire.available (); i++){
      pIdent[i] = Wire.receive(); // receive byte as an integer
    }
    if(i == WII_TELEGRAM_LEN){ rc = 0; }
  }
  return rc;
}

void clearTwiInputBuffer(void){
  while( Wire.available ())
  Wire.receive ();
}

void send_zero (){
  for(byte i = 0; i < 3; i++){
    Wire.beginTransmission (WII_NUNCHUCK_TWI_ADR); // transmit to device 0x52
    Wire.send (0x00); // sends one byte
    Wire.endTransmission (); // stop transmitting
  }
}

int t = 0;
void loop (){
  t++;
  long last = millis();
  if( t == 1) {
    t = 0;
    Wire.requestFrom (WII_NUNCHUCK_TWI_ADR, WII_TELEGRAM_LEN); // request data from nunchuck
    for (cnt = 0; (cnt < WII_TELEGRAM_LEN) && Wire.available (); cnt++){
      outbuf[cnt] = nunchuk_decode_byte (Wire.receive ()); // receive byte as an integer
      digitalWrite (ledPin, HIGH); // sets the LED on
    }
    clearTwiInputBuffer();
    if (cnt >= WII_TELEGRAM_LEN){
      print ();
      if (c_button && z_button){ muovi(); }
    }
    send_zero ();
  }
  updateServo();
  delay (20);
}

void z (){ 
  if (!z_button){
    servoPos1=locZx;                  // sets the servo position according to the scaled value 
    servoPos2=locZy;                  // sets the servo position according to the scaled value 
    myservo1.write(servoPos1);                  // sets the servo position according to the scaled value 
    myservo2.write(servoPos2);                  // sets the servo position according to the scaled value 
    delay(500);                           // waits for the servo to get there 
  }
}
void c (){ 
  if (!c_button){
    servoPos1=locCx;                  // sets the servo position according to the scaled value 
    servoPos2=locCy;                  // sets the servo position according to the scaled value 
    myservo1.write(servoPos1);                  // sets the servo position according to the scaled value 
    myservo2.write(servoPos2);                  // sets the servo position according to the scaled value 
    delay(500);                           // waits for the servo to get there 
  }
}

void print (){
  int joy_x_axis = outbuf[0];
  int joy_y_axis = outbuf[1];
  int accel_x_axis = outbuf[2];// * 2 * 2
  int accel_y_axis = outbuf[3];// * 2 * 2
  int accel_z_axis = outbuf[4];// * 2 * 2
  z_button = 0;
  c_button = 0;
  if ((outbuf[5] >> 0) & 1){ z_button = 1; z(); }
  if ((outbuf[5] >> 1) & 1){ c_button = 1; c(); }

  Serial.print (joy_x_axis, DEC);Serial.print ("\t");
  Serial.print (joy_y_axis, DEC);Serial.print ("\t");
  Serial.print (accel_x_axis, DEC);Serial.print ("\t");
  Serial.print (accel_y_axis, DEC);Serial.print ("\t");
  Serial.print (accel_z_axis, DEC);Serial.print ("\t");
  Serial.print (z_button, DEC);Serial.print ("\t");
  Serial.println (c_button, DEC);

  if(
    (joy_x_axis == 255) && 
    (joy_y_axis == 255) && 
    (accel_x_axis == 255) && 
    (accel_y_axis == 255) && 
    (accel_z_axis == 255) && 
    (c_button == 1) && 
    (z_button == 1)
  ){ 
    Serial.println("\tError: Outof sync.");
    Serial.println("----RESET----");
    delay(500);
  }
}

char nunchuk_decode_byte (char x){
  #ifndef USE_NEW_WAY_INIT
    x = (x ^ 0x17) + 0x17;
  #endif
  return x;
}

void muovi (){
  float serv1 = outbuf[0];// joy x 0-255 
  if (serv1 < 200 && serv1 > 50){
    // centered
  } else if (serv1 > 250){
    servoPos1=servoPos1-5;
  } else if (serv1 > 200){
    servoPos1=servoPos1-2;
  } else if (serv1 < 5){
    servoPos1=servoPos1+5;
  } else if (serv1 < 50){
    servoPos1=servoPos1+2;
  }
    
  float serv2 = outbuf[1];// joy y 0-255
  if (serv2 < 200 && serv2 > 50){
    // centered
  } else if (serv2 > 250){
    servoPos2=servoPos2+5;
  } else if (serv2 > 200){
    servoPos2=servoPos2+2;
  } else if (serv2 < 5){
    servoPos2=servoPos2-5;
  } else if (serv2 < 50){
    servoPos2=servoPos2-2;
  }
  if (servoPos1 < 0){ servoPos1 = 0; }
  if (servoPos1 > 179){ servoPos1 = 179; }
  if (servoPos2 < 0){ servoPos2 = 0; }
  if (servoPos2 > 179){ servoPos2 = 179; }

Serial.print (servoPos1, DEC);
Serial.print ("\t");
Serial.print (servoPos2, DEC);
Serial.print ("\t");
Serial.print ("\r\n");
  //servoPos1 = map(serv1, 0, 255, 179, 0);// scale it to use it with the servo (value between 0 and 180) 
  //servoPos2 = map(serv2, 0, 255, 0, 179);// scale it to use it with the servo (value between 0 and 180) 
}

void updateServo() {
  digitalWrite (ledPin, HIGH); // laser on
  delay(10);
  digitalWrite (ledPin, LOW); // laser off

  myservo1.write(servoPos1);                  // sets the servo position according to the scaled value 
  myservo2.write(servoPos2);                  // sets the servo position according to the scaled value 
  delay(250);                           // waits for the servo to get there 
}

/*
void updateServo() {

    if (millis() - lastPulse >= refreshTime) {

        digitalWrite(servoPin, HIGH);
        delayMicroseconds(pulseWidth);
        digitalWrite(servoPin, LOW);

        digitalWrite(servoPin2, HIGH);
        delayMicroseconds(pulseWidth2);
        digitalWrite(servoPin2, LOW);

        lastPulse = millis();
    }
}

void muovi (){
    float tilt = (700 - outbuf[1]*2); // outbuf[3]
    float tilt2 = outbuf[0]*2; // outbuf[2]

    tilt = (tilt);
    pulseWidth = (tilt * 5) + minPulse;

    tilt2 = (tilt2-288);
    pulseWidth2 = (tilt2 * 5) + minPulse2;

    pwbuff[pwbuffpos] = pulseWidth;
    pwbuff2[pwbuffpos2] = pulseWidth2;
    
    if( ++pwbuffpos == pwbuffsize ) pwbuffpos = 0;
    if( ++pwbuffpos2 == pwbuffsize ) pwbuffpos2 = 0;


    pulseWidth=0;
    pulseWidth2=0;

    for( int p=0; p<pwbuffsize; p++ ){
        pulseWidth += pwbuff[p];
        pulseWidth2 += pwbuff2[p];
    }

    pulseWidth /= pwbuffsize;
    pulseWidth2 /= pwbuffsize;

}
*/
