/* HCSR04UltrasonicDistanceSensorv1 * * Basic sketch to learn how the HC-SR04 sensor works * The sketch works but because it uses delay() would be harder to integrate with other components or sensors. * * pins used * pin 7 to Trig Pin * pin 6 to Echo pin */ //const int is a constant integer that cannot have it's value changed. const int triggerPin = 7; const int echoPin = 6; //An unsigned long is needed because the numbers produced can be much larger //than an int can hold (max value 32,767) unsigned long duration; //time taken for echo int distance; //in mm void setup() { Serial.begin(9600); Serial.println("HCSR04UltrasonicDistanceSensorv1..."); Serial.println(" ");//Blank line //pinMode set for OUTPUT...sending HIGH of LOW pinMode(triggerPin, OUTPUT); //sends signal //pinMode set for INPUT, we will receive an incoming HIGH or LOW on this pin pinMode(echoPin, INPUT); //receives signal } void loop() { // Clears the trigPin condition, just in case it had been left HIGH //Same as turing the LED off in the blink sketch digitalWrite(triggerPin, LOW); //A tiny delay 2 millionths of a second delayMicroseconds(2); // Sets the trigPin HIGH (ACTIVE) for 10 microseconds //same as turing the LED on in the blink sketch digitalWrite(triggerPin, HIGH); //pin stays HIGH (5v) for 10 microseconds to trigger a pulse delayMicroseconds(10); //Pin taken LOW (0v) after pulse triggered ready for next pulse digitalWrite(triggerPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds //Pulse in HIGH waits for the echoPin to go HIGH (5v) and then starts a timer until it goes LOW //At that point the HC-SR04 has received it's set of echos duration = pulseIn(echoPin, HIGH); // Calculating the distance // Speed of sound wave divided by 2 as the sound travels to and from the object distance = duration * 0.34 / 2; // Displays the distance on the Serial Monitor Serial.print("Distance: "); Serial.print(distance); Serial.println(" mm"); //wait 1 second before runing the code again delay(1000); }