SunFounder ESP32 Starter Kit
1. Loop to read distance and update parameters
In the loop, the code first reads the distance measured by the ultrasonic module and updates the
interval parameter based on the distance.
// Update the distance
distance = readDistance();
// Update intervals based on distance
if (distance <= 10) {
intervals = 300;
} else if (distance <= 20) {
intervals = 500;
} else if (distance <= 50) {
intervals = 1000;
} else {
intervals = 2000;
}
2. Check if it’s time to beep
The code calculates the difference between the current time and the previous beep time, and if the
difference is greater than or equal to the interval time, it triggers the buzzer and updates the previous
beep time.
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= intervals) {
Serial.println("Beeping!");
beep();
previousMillis = currentMillis;
}
3. Update LCD display
The code clears the LCD display and then displays “Dis:” and the current distance in centimeters on
the first line.
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Dis: ");
lcd.print(distance);
lcd.print(" cm");
delay(100);
1.34 6.4 Digital Dice
This project builds upon the 2.5 Number Display project by adding a button to control the digit displayed on the seven-
segment display.
In this project, a random number is generated and displayed on the seven-segment display to simulate a dice roll. When
the button is pressed, a stable number (randomly selected from 1 to 6) is displayed on the seven-segment display.
Pressing the button again will initiate the simulation of a dice roll, generating random numbers as before. This cycle
continues each time the button is pressed.
1.34. 6.4 Digital Dice 117