#include <NewPing.h>
#include <Tone.h>

// Broches du capteur HC-SR04
const int trigPin = A0; // Broche TRIG
const int echoPin = A4; // Broche ECHO
const int RED_LED_PIN = D4;    // Broche pour la LED rouge
const int ORANGE_LED_PIN = D6; // Broche pour la LED orange
const int GREEN_LED_PIN = D5;  // Broche pour la LED verte
const int BUZZER_PIN = A7;     // Broche pour le buzzer
// Broche du bouton-poussoir
const int buttonPin = A2; 
NewPing sonar(trigPin, echoPin); 

void setup() {
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin;INPUT);
  pinMode(ORANGE_LED_PIN, OUTPUT);
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); 

  Serial.begin(1152000);
}
void loop(){ 
 int buttonState = digitalRead(buttonPin);
 
  if (buttonState == LOW) 
  {

    
  unsigned int distance = sonar.ping_cm(); 
  Serial.println("Distance: ");
  Serial.println(distance);
  Serial.println("cm");
 
  
    if (distance<=30)
     {
      digitalWrite(RED_LED_PIN, HIGH);
      digitalWrite(ORANGE_LED_PIN, LOW);
      digitalWrite(GREEN_LED_PIN, LOW);     
      tone(BUZZER_PIN, 440, 0);
     }
     else if  (distance>30.0 && distance<120.0 )
     {    
      
      digitalWrite(RED_LED_PIN, LOW);
      digitalWrite(GREEN_LED_PIN, LOW);
      int x = map(distance, 30, 120, 100, 1000);
      digitalWrite(ORANGE_LED_PIN, HIGH);
      tone(BUZZER_PIN, x ,300);
     } 
      
    else if (distance>=120)
     {
      digitalWrite(RED_LED_PIN, LOW);
      digitalWrite(ORANGE_LED_PIN, LOW);
      digitalWrite(GREEN_LED_PIN, HIGH);
      noTone(BUZZER_PIN);
     }  
  }
  else{
    digitalWrite(RED_LED_PIN, LOW);
      digitalWrite(ORANGE_LED_PIN, LOW);
      digitalWrite(GREEN_LED_PIN, LOW);
      noTone(BUZZER_PIN);
    }
  
}