The sensor circuit with HC-SR04 Distance and Proximity Sensor Program


The sensor circuit with HC-SR04 Distance


  1. VCC on the HC-SR04 is connected to + 5V on the Arduino board
  2. GND connected to GND
  3. Pin Trig (Trigger) is connected to pin 10 on the Arduino board
  4.  Pin Echo is connected to pin 9 on the Arduino board

// Free Tutorial Arduino
// www.ioisalman.com


// Trigger pin 9
// Pin 10 echo
const int pTrig = 9;
const int Pecho = 10;

void setup () {
   Serial.begin (9600);
   pinMode (pTrig, OUTPUT);
   pinMode (Pecho, INPUT);
}

long duration = 0;
void loop () {
   // Trigger for 10us
   digitalWrite (pTrig, HIGH);
   delayMicroseconds (10);
   digitalWrite (pTrig, LOW);
  
   duration = pulseIn (Pecho, HIGH);
   Serial.print ("Duration");
   Serial.print (duration);
  
   Serial.print ("Distance");
   Serial.println ((duration * 0.034) / 2);
   delay (1000);
}


Program in sketch above will enable pin Trigger for 10μs, then will wait until Echo pin HIGH worth. Examine the line to 23.

duration = pulseIn (Pecho, HIGH);

PulseIn function () will instruct the system to wait until the pin Echo worth HIGH. Long waiting process will be considered as the duration of delivery + reception echo signal reflected by the object.

A little explanation about pulseIn function (), this function defaults have 3 parameters, and Value 2 Pin parameters and 1 parameter Timeout as an additional parameter

pulseIn(Pin, Value);
pulseIn(Pin, Value, Timeout);

In the Value parameter, we can enter the HIGH or LOW, so the Arduino will wait until the conditions are met. While Timeout used when in a certain time condition has not been fulfilled. That is the basis of making the proximity sensor with ultrasonic sensor HC-SR04.

Subscribe to receive free email updates:

0 Response to "The sensor circuit with HC-SR04 Distance and Proximity Sensor Program"

Post a Comment