// Déclaration des constantes et variables

const int PinPOT = 0;
const int PinTone = 8;
const int PinButton = 12;

int State = 0;
int ValButton = 0;
int OldValButton = 0;
int ValPot = 0;
int Coeff=0;


// Initialisation des entrées et sorties

void setup() {
  Serial.begin(9600);
  pinMode (PinButton, INPUT);
  while(Coeff<1 || Coeff>4)  
  { 
  int Val=0; 
  char tampon[10]="";      
  Serial.println("Veuillez choisir la gamme de frequence (valeur entre 1 et 4):");
  Serial.println("1 : 0 - 1023 Hz :");
  Serial.println("2 : 0 - 2046 Hz :");
  Serial.println("3 : 0 - 3069 Hz :");
  Serial.println("4 : 0 - 4092 Hz :");
  Serial.println(" ");
  while(!Val)  
    { 
    delay(200); 
    Val=Serial.available();
    }
  for (int i=0; i < Val; i++)
    { 
    tampon[i]=Serial.read();
    delay(15); 
    } 
  Coeff = atoi(tampon); 
  }
  Serial.print("Gamme de frequence choisie : "); Serial.println(Coeff);
}


// 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 = analogRead(PinPOT);
    tone(PinTone, ValPot*Coeff);
  }
  else {
    noTone(PinTone);
  }
}
