Arduino Sensor Demonstrations: Difference between revisions

From sandbox
Jump to navigation Jump to search
No edit summary
No edit summary
Line 9: Line 9:


==== Datasheet ====
==== Datasheet ====
{{#widget:PDF
|url=https://www.mediawikiwidgets.org/w/images/8/80/20171004_Beginners_tutorial_to_Semantic_MediaWiki.pdf
|width=750
|height=1050
}}


{{#widget:PDF
{{#widget:PDF

Revision as of 20:07, 22 December 2021

PIR Sensor

HC-SR04 Ultrasonic Distance Sensor

Introduction

The HC-SR04 Ultrasonic Sensor measures distance by emitting 40kHz tone which travels through the air and bounces back from any object or obstacle it encounters. If the reflected tone is received by the module, the distance to the reflecting object can be calculated from the travel time.

Datasheet

Currently your browser does not use a PDF plugin. You may however download the PDF file instead.

Currently your browser does not use a PDF plugin. You may however download the PDF file instead.

https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf


Example Code


// ---------------------------------------------------------------- //
// Arduino Ultrasoninc Sensor HC-SR04
// Re-writed by Arbi Abdul Jabbaar
// Using Arduino IDE 1.8.7
// Using HC-SR04 Module
// Tested on 17 September 2019
// ---------------------------------------------------------------- //

#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");
}
void loop() {
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
}