/* HCSR04UltrasonicDistanceSensorv3Function * * The goal of this sketch is to use multiple HC-SR04 modules triggering at independant intervals * * pins used * pin 7 to Trig Pin...sensor 1 * pin 6 to Echo pin...sensor 1 * pin 5 Trig pin...sensor 2 * pin 4 Echo pin...sensor 2 * pin 3 Trig pin...sensor 3 * pin 2 Echo pin...sensor 3 */ //Global Variables //const int is a constant integer that cannot have it's value changed. const int triggerPin = 7; const int echoPin = 6; const int triggerPin2 = 5; const int echoPin2 = 4; const int triggerPin3 = 3; const int echoPin3 = 2; //the three timers unsigned long sensorTimer1; unsigned long sensorTimer2; unsigned long sensorTimer3; //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("HCSR04UltrasonicDistanceSensorv3Function..."); 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 //more pinModes for 2 more sensors pinMode(triggerPin2, OUTPUT); //sends signal pinMode(echoPin2, INPUT); //receives signal pinMode(triggerPin3, OUTPUT); //sends signal pinMode(echoPin3, INPUT); //receives signal } void loop() { //Local variable int distance; //in mm if(millis() > sensorTimer1){ sensorTimer1 = millis() + 1600; distance = getDistanceHCSSR04(triggerPin,echoPin); // Displays the distance on the Serial Monitor Serial.print(" Sensor 1 Distance: "); Serial.print(distance); Serial.println(" mm"); } if(millis() > sensorTimer2){ sensorTimer2 = millis() + 1500; //different set of pins passed to function distance = getDistanceHCSSR04(triggerPin2,echoPin2); // Displays the distance on the Serial Monitor Serial.print(" Sensor 2 Distance: "); Serial.print(distance); Serial.println(" mm"); } if(millis() > sensorTimer3){ sensorTimer3 = millis() + 1400; //different set of pins passed to function distance = getDistanceHCSSR04(triggerPin3,echoPin3); // Displays the distance on the Serial Monitor Serial.print(" Sensor 3 Distance: "); Serial.print(distance); Serial.println(" mm"); } }