My code does not work when i connect buzzer & LED before uploading

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()
  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);
  digitalWrite(trigPin, HIGH);
  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.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.

@izzu.asj Please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly.
Triple backticks look like this:

Copy and paste these if you can’t find the correct symbol on your keyboard.

Also, please explain how this has anything to do with Blynk.


Hello Pete,

My device is not online on Blynk and nothing works if i upload this code when i connect the buzzer and LED before uploading. But when i upload without connecting the buzzer and LED it can be online on Blynk and i have to connect the buzzer and LED afterwards for them to work.


That’s because you have no Blynk libraries in your sketch, and no Blynk connection/authentication cod in there either.

Very few ESP8266 boards have a pin labelled D9. It’s usually labelled Rx and is GPIO3, which is used when uploading code via the USB port.
This is why your upload isn’t working.