Ultrasonic sensor with buzzer

This is the code for an ultrasonic sensor with buzzer. Someone wanted to get code of two ultrasonic sensors, but unfortunately my other ultrasonic sensor broke so I could experiment with it.
The sketch
int greenled = 3;
int redled = 4;

int trigPin = 5;
int echoPin = 6;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenled, OUTPUT);
  pinMode(redled, OUTPUT);

void firstsensor(){ // This function is for first sensor.
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;

      Serial.print("1st Sensor: ");
      Serial.print("cm    ");

  if (distance > 10) {  // Change the number for long or short distances.
    digitalWrite (greenled, HIGH);
      digitalWrite (redled, LOW);
} else {
     digitalWrite (greenled, LOW);
     digitalWrite (redled, HIGH);

void loop() {


  1. it would be helpfull if the diagram was not blocked by youtubes dumb video recomendations at the end of this video so we can see the circuit diagram

    1. How about helping the content creator at least with some support?


To the shamless spammers (Mithra, srihariparu, venusha) don't you have any brain-cells? You can see that none of your spam comments are getting published yet you still keep commenting your garbage.

Newly posted:
How to read instagram messages without opening |Self-checkouts vs cashiers (Old vs Young)