#include "LiquidCrystal_I2C.h"
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
// Define pin connections
#define TRIG_PIN D9
#define ECHO_PIN D8
#define BUZZER_PIN D10
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
void setup() {
Serial.begin(115200);
Serial.println("Hello, STM32!");
lcd.init();
lcd.backlight();
lcd.setCursor(4, 0);
lcd.print("Hello, STM32");
lcd.setCursor(5, 2);
lcd.print("Welcome to");
lcd.setCursor(7, 3);
lcd.print("Wokwi!");
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Set up the buzzer pin
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
long duration, distance;
// Clear the trigPin
// digitalWrite(TRIG_PIN, LOW);
//delayMicroseconds(5);
// Sets the trigPin on HIGH state for 10 microseconds
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(ECHO_PIN, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Set the cursor to column 0, line 1
lcd.setCursor(10, 0);
lcd.print(" ");
lcd.setCursor(10, 0);
lcd.print(distance);
lcd.print(" cm");
// Check if distance is within threshold
if (distance < 20) {
digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(BUZZER_PIN, LOW);
}
delay(500);
}
Loading
st-nucleo-l031k6
st-nucleo-l031k6