The code below does not work when i connect a buzzer and LED to the board before uploading to my board. But when i connect the buzzer and LED manually after i upload it works. The project is to create a measuring device using an ultrasonic sensor. The buzzer and LED is used to alert when the distance is more than 30 cm. Can someone help show me what’s wrong and how to make it work without manually connect the buzzer and LED.
#define trigPin D6 // Trigger Pin
#define buzzerPin D8 // Buzzer Pin
#define ledPin D9 // LED Pin
long duration, distance; // Duration used to calculate distance
void setup()
{
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT); // Set buzzer pin as output
pinMode(ledPin, OUTPUT); // Set LED pin as output
}
void loop()
{
// Trigger the ultrasonic sensor to measure distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance (in cm) based on the speed of sound.
distance = duration / 58.2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check distance and activate buzzer if more than 30 centimeters
if (distance > 30) {
tone(buzzerPin, 1000); // Send 1KHz sound signal...
digitalWrite(ledPin, HIGH); // ...and turn on the LED
delay(1000); // ...for 1 sec
}
else {
noTone(buzzerPin); // Stop sound...
digitalWrite(ledPin, LOW); // ...and turn off the LED
delay(1000); // ...for 1 sec
}
// Delay 50ms before the next reading.
delay(1000);
}```