Arduino Basics: The ultrasonic sensor


The ultrasonic sensor allow us to measure distances by sending ultrasonic waves and receiving them back to calculate the time between the emision and reception. 

This have a lot of utilities but in this case I'm just focusing on measuring the distance from the sensor to common objects.

const int Trigger=2;
const int Echo=3;
int last=0;
 
void setup() {
  Serial.begin(9600);
  pinMode(Trigger,OUTPUT);
  pinMode(Echo,INPUT);
  digitalWrite(Trigger,LOW);
}
 
void loop(){
  long t;
  long d;

  digitalWrite(Trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trigger, LOW);
 
  t = pulseIn(Echo, HIGH);
  d = t/59;

  if(last!=d){
    Serial.print("-> Distance: ");
    Serial.print(d);
    Serial.println("cm");
    last=d;
  }
  delay(200);
}

Comments

Post a Comment