#include "Ultrasonic.h"

int pinTrig = 9;
int pinEcho = 8;
int ledPinGreen = 11;
int ledPinRed = 12;
int limitGreen = 10;
int limitRed = 18;
int pinBuzzer = 6;

String methodeNotification = "leds";

Ultrasonic ultrasonic(pinTrig, pinEcho);

long temps;
float distance;

void setup() {
    pinMode(pinTrig, OUTPUT);
    pinMode(pinEcho, INPUT);
    pinMode(pinBuzzer, OUTPUT);
    pinMode(ledPinGreen, OUTPUT);
    pinMode(ledPinRed, OUTPUT);

    digitalWrite(pinTrig, LOW);

    Serial.begin(9600);
}

void loop() {
    digitalWrite(pinTrig, HIGH);
    delayMicroseconds(10);
    digitalWrite(pinTrig, LOW);

    temps = pulseIn(pinEcho, HIGH);

    if (Serial.available() > 0) {
        String msg = Serial.readString();
        methodeNotification = msg;
    }

    if (temps > 25000){
        Serial.println("Out of range");
        digitalWrite(ledPinGreen, LOW);
        digitalWrite(ledPinRed, LOW);
        noTone(pinBuzzer);
        /*digitalWrite(ledPinGreen, HIGH);
        digitalWrite(ledPinRed, HIGH);
        tone(pinBuzzer, 1000); */
    }
    else{
        temps = temps / 2;
        distance = temps * 340 / 10000.0;
        // Serial.print("Temps : ");
        // Serial.print(temps);
        // Serial.println(" µs");

        /*Serial.print("Distance : ");
        Serial.print(distance);
        Serial.println(" cm");*/

        int dist = ultrasonic.distanceRead(CM);
        Serial.print("Ultrasonic Distance : ");
        Serial.print(distance);
        Serial.println(" cm");

        if (distance < limitRed && methodeNotification == "sound") {
            digitalWrite(ledPinGreen, LOW);
            digitalWrite(ledPinRed, HIGH);
            noTone(pinBuzzer);
        }
        else if (distance < limitRed && methodeNotification == "leds") {
            digitalWrite(ledPinGreen, LOW);
            digitalWrite(ledPinRed, HIGH);
            noTone(pinBuzzer);
        }
        else if (distance > limitRed && methodeNotification == "sound") {
            digitalWrite(ledPinGreen, HIGH);
            digitalWrite(ledPinRed, HIGH);
            tone(pinBuzzer, 1000);
        }
        else if (distance > limitRed && methodeNotification == "leds") {
            digitalWrite(ledPinGreen, HIGH);
            digitalWrite(ledPinRed, LOW);
            noTone(pinBuzzer); 
        }
        else {
            digitalWrite(ledPinGreen, LOW);
            digitalWrite(ledPinRed, LOW);
            noTone(pinBuzzer);
        }
    }
    delay(500);
}

