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(distance);
      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() {
Serial.println("\n");
firstsensor();
delay(100);
}




2 comments:

  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

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

      Delete



Newly posted:
Reason why rich getting richer and poor getting poorer