Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define echoPin 49 // attach pin D2 Arduino to pin Echo of HC-SR04
- #define trigPin 51 //attach pin D3 Arduino to pin Trig of HC-SR04
- // defines variables
- long duration; // variable for the duration of sound wave travel
- float 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
- pinMode(53, OUTPUT);
- pinMode(47, OUTPUT);
- Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
- digitalWrite(53, HIGH); //these pins are used to provide power to the sensor.
- digitalWrite(47, LOW);
- }
- void loop() {
- Serial.print("Distance: ");
- Serial.print(GetDistance());
- Serial.println(" cm");
- }
- float GetDistance(){
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH);
- distance = duration * 0.034 / 2;
- return distance;
- }
Add Comment
Please, Sign In to add comment