#define PIN_BUTTON A1  
#define PIN_TRIG A3
#define PIN_ECHO A2
#define vert A4
#define rouge A0 
#define BUZZER_PIN A5

void setup() {
  Serial.begin(115200);
  pinMode(PIN_BUTTON, INPUT_PULLUP);  
  pinMode(PIN_TRIG, OUTPUT);
  pinMode(PIN_ECHO, INPUT);
  pinMode(rouge, OUTPUT);
  pinMode(vert, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT); // Set the buzzer pin as an output
}

void loop() {
  while (digitalRead(PIN_BUTTON) == HIGH) {
    delay(10);
  }

  // Start a new measurement:
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);

  int duration = pulseIn(PIN_ECHO, HIGH);
  float distance = duration / 58.0;  
  Serial.print("Distance en CM: ");
  Serial.println(distance);
  
  if (distance < 40) {
    digitalWrite(BUZZER_PIN, HIGH); // Turn the buzzer on
    digitalWrite(rouge, HIGH);
    digitalWrite(vert, LOW);
    delay(500); // Buzz for 0.5 seconds
    digitalWrite(BUZZER_PIN, LOW); // Turn the buzzer off
  }
  else if (distance >= 40 && distance <= 120) {
    digitalWrite(BUZZER_PIN, HIGH); // Turn the buzzer on
    digitalWrite(rouge, LOW);
    digitalWrite(vert, LOW);
    delay(500); // Buzz for 0.5 seconds
    digitalWrite(BUZZER_PIN, LOW); // Turn the buzzer off
  }
  else {
    digitalWrite(BUZZER_PIN, HIGH); // Turn the buzzer on
    digitalWrite(rouge, LOW);
    digitalWrite(vert, HIGH);
    delay(500); // Buzz for 0.5 seconds
    digitalWrite(BUZZER_PIN, LOW); // Turn the buzzer off
  }
  
  while (digitalRead(PIN_BUTTON) == LOW) {
    delay(10);
  }
  
  delay(100);
}
Loading
st-nucleo-l031k6