// Déclaration des constantes et variables

int TRIGGER_PIN = 8; 
int ECHO_PIN = 9;
const int PinButton = 7;   

const unsigned long MEASURE_TIMEOUT = 25000UL;

int ValButton = 0;
int OldValButton = 0;
int State = 0;
int OldState = 0;

int Distance = 0;
int DistanceMesure = 0;
long Dt = 0;

float Temp = 20.0;
float VitTheoUS = 20.05*(sqrt(Temp+273.15));


// Initialisation des entrées et sorties

void setup() 
{  
Serial.begin(9600);
pinMode(PinButton,INPUT);
pinMode(TRIGGER_PIN, OUTPUT);
digitalWrite(TRIGGER_PIN, LOW); 
pinMode(ECHO_PIN, INPUT);
Serial.println("Appuyez sur le bouton poussoir pour mesurer \
la distance entre le capteur et l'obstacle.");
}


// Fonction principale en boucle

void loop() 
{
ValButton = digitalRead(PinButton);
delay(10);

if ((ValButton == HIGH)&&(OldValButton == LOW)) 
  {
  State=1-State;
  }
OldValButton = ValButton;

if (State==1) 
{
  if (OldState == 0)
  {
   Serial.println("Mesure de la distance en cours.");
   Serial.println("");
   Serial.println ("Distance (cm) :");
   OldState=1;
  }

  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);
  Dt = pulseIn(ECHO_PIN, HIGH, MEASURE_TIMEOUT);
  
  Distance = int(Dt / 2.0 * VitTheoUS/ 10000);

  if (DistanceMesure != Distance)
  {
  Serial.println(Distance);
  DistanceMesure = Distance;
  }
  Serial.flush();
  delay(100);
}
else
{
  if (OldState == 1){
  Serial.println("Fin des mesures.");
  OldState = 0;}
}   
}
