// Déclaration des constantes et variables

const int PinButton = 7; 
const int PinTone = 3;
const int PinLed = 4; 

const unsigned long MEASURE_TIMEOUT = 25000UL;

int TRIGGER_PIN = 8; 
int ECHO_PIN = 9;

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

int Distance = 0;
int DistanceMesure = 0;
int DistanceAlarme = 10;
long Dt = 0.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(PinLed,OUTPUT);
pinMode(TRIGGER_PIN, OUTPUT);
digitalWrite(TRIGGER_PIN, LOW); 

if (ECHO_PIN != TRIGGER_PIN){
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;
  }

  if (ECHO_PIN != TRIGGER_PIN){
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);
  Dt = pulseIn(ECHO_PIN, HIGH, MEASURE_TIMEOUT);}
  else {
  pinMode(TRIGGER_PIN, OUTPUT);
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(5);
  digitalWrite(TRIGGER_PIN,LOW);
  pinMode(TRIGGER_PIN,INPUT);
  Dt = pulseIn(TRIGGER_PIN,HIGH);}
  
  Distance = int(Dt / 2.0 * VitTheoUS/ 10000);

  if (DistanceMesure != Distance)
  {
  Serial.println(Distance);
  DistanceMesure = Distance;
  }
  if (Distance < DistanceAlarme)
   {
      digitalWrite(PinLed, HIGH);
      tone(PinTone,440);
      delay(100);
      digitalWrite(PinLed, LOW);
      noTone(PinTone);
      delay(100);
   }
   else
   {
      digitalWrite(PinLed, LOW);
      noTone(PinTone);
   }
  Serial.flush();
  delay(100);
}
else
{
  if (OldState == 1){
  Serial.println("Fin des mesures.");
  OldState = 0;}
}   
}
