// Declare variables for duration and distance
float distance;
float duration;
void setup() {
// Begin serial communication with the baud rate of 9600 bits per second
Serial.begin(9600);
// Set up the pins for the ultrasonic sensor, LED, and buzzer
pinMode(PA0, OUTPUT); // Trigger pin for Ultrasonic sensor (adjust based on your STM32 pin)
pinMode(PA1, INPUT); // Echo pin for Ultrasonic sensor (adjust based on your STM32 pin)
pinMode(PA2, OUTPUT); // LED pin (adjust based on your STM32 pin)
pinMode(PA3, OUTPUT); // Buzzer pin (adjust based on your STM32 pin)
}
void loop() {
// Send a HIGH signal to trigger the ultrasonic sensor
digitalWrite(PA0, HIGH);
delayMicroseconds(10); // Wait for 10 microseconds
digitalWrite(PA0, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(PA1, HIGH);
// Calculate the distance based on the duration
distance = duration * 0.017;
// If the distance is less than 50 cm, turn on the LED and buzzer
if (distance < 50) {
digitalWrite(PA2, HIGH); // Turn on LED
digitalWrite(PA3, HIGH); // Turn on buzzer
} else {
// Otherwise, turn off the LED and buzzer
digitalWrite(PA2, LOW); // Turn off LED
digitalWrite(PA3, LOW); // Turn off buzzer
}
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Small delay before next reading
delay(500);
}