#define NUMBER_OF_SENSORS 7 // Number of ultrasonic sensors
#define MAX_SENSOR_MEASUREMENT 35 // max distance for read for the sensor (in cm)
// for ultrasonic
int sensorsPins[NUMBER_OF_SENSORS] = {2, 11, 12, A0, A1, A2, A3}; //define the pins for the sensors
const int TRIG_PIN = 13; // TRIGGER pin
volatile int currentSensor = 0; // current sensor been red
boolean sensorState[NUMBER_OF_SENSORS];//holds the sensor state to create a "snap shot" of the state of all the sensors after full loop over them - so we can choose the higher one.
long duration, distanceCm; // declare var for sensor read
// VOID SETUP
void setup() {
// setup for ultrasonic
pinMode(TRIG_PIN, OUTPUT);
for (int i = 0; i < NUMBER_OF_SENSORS; i++) {
pinMode(sensorsPins[i], INPUT);
} //end for
} // end void setup
void loop() {
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(sensorsPins[currentSensor], HIGH, 4000);
// convert the time into a distance
distanceCm = duration / 29.1 / 2 ;
// if the distnace is between 40 and more then 0 (also the vlaue that OUT OF RANGE returns) show true - as sensor is showing movment.
if (distanceCm < MAX_SENSOR_MEASUREMENT && distanceCm > 0) {
sensorState[currentSensor] = true; // set true
} else {
sensorState[currentSensor] = false; // set false
} //end if
// move to next sensor
currentSensor = (currentSensor + 1) % NUMBER_OF_SENSORS;
}
Comments