/* HCSR04UltrasonicDistanceSensorv2Function * * The goal of this sketch is to make the distance reading from the module into a function * The function needs to be able to use multiple HC-SR04 modules if needed (front and rear) * Basic sketch to learn how the HC-SR04 sensor works * * 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; //Global Variable unsigned long sensorTimer1; //Function to trigger a sensor //It receives the pins of the sensor and send back the distance int getDistanceHCSSR04(int funcTriggerPin, int funcEchoPin){ //An unsigned long is needed because the numbers produced can be much larger //than an int can hold (max value 32,767) //Local variables unsigned long duration; //time taken for echo int myDistance; digitalWrite(funcTriggerPin, 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(funcTriggerPin, 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(funcTriggerPin, LOW); duration = pulseIn(funcEchoPin, HIGH); myDistance = duration * 0.34 / 2; return myDistance; } void setup() { Serial.begin(9600); Serial.println("HCSR04UltrasonicDistanceSensorv2Function..."); 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() { //Local variable int distance; //in mm if(millis() > sensorTimer1){ sensorTimer1 = millis() + 1000; distance = getDistanceHCSSR04(triggerPin,echoPin); // Displays the distance on the Serial Monitor Serial.print("Distance: "); Serial.print(distance); Serial.println(" mm"); } }