// Déclaration des constantes et variables

const int PinButton = 12;
const int PinTone = 3;
const int PinPot[] = {1,2};

int ValButton=0;
int OldValButton=0;
int State = 0;
int ValPot[] = {0,0};
int FreqWave=0;


// Définition de fonctions

String dec2bin(int d){
String b;
    if (d == 0){
        b = "0";
        }
    else{
        b = "";
        while (d != 0){
            b = "01"[d & 1] + b;
            d = d >> 1;}
    }
    return b;
}

int bin2dec(String b){
int i, len;
int result=0;
len = b.length();
for(i=0; i<len; i++)
  {
    result = result*2+int(b[i]- '0');
  }
return result;
}

int CalculFreq(int valpot1, int valpot2){
String valpot1bin, valpot2bin;
int Freq;
    valpot1bin = dec2bin(int(valpot1/4));
    valpot1bin= valpot1bin+"0000";
    valpot2bin = dec2bin(int(valpot2/4));
    valpot2bin = "0000"+dec2bin(int(valpot2/4));
    Freq = bin2dec(valpot1bin) + bin2dec(valpot2bin);
    return Freq ;
}


// Initialisation des entrées et sorties

void setup() {  
  pinMode (PinButton, INPUT);
}


// Fonction principale en boucle

void loop() {
  ValButton = digitalRead(PinButton);
  delay(10);
  if ((ValButton == HIGH) and (OldValButton==LOW)) {
    State = 1 - State;  
  }
  OldValButton = ValButton;
  if (State==1){
    ValPot[0]= analogRead(PinPot[0]);
    ValPot[1]= analogRead(PinPot[1]);
    FreqWave = CalculFreq(int(ValPot[0]), int(ValPot[1])); 
    tone(PinTone, FreqWave);
  }
  else{
    noTone(PinTone);
  }
}
