/* * Detect distance with IR sensors */ #include // Include servo library const int irLeftPin = A0; // Set left IR sensor to analog pin A0 const int irRightPin = A5; // Set right IR sensor to analog pin A5 /* * Built-in initialization block */ void setup() { Serial.begin(9600); // Start Serial port, and set baud rate to 9600 } /** * Main loop auto-repeats **/ void loop() { int irLeft = irDetect(irLeftPin); // Check for object on left int irRight = irDetect(irRightPin); // Check for object on right Serial.print(irLeft); // Print left IR sensor reading Serial.print(" "); Serial.println(irRight); // Print right IR sensor reading } /********** ************** ********** Functions ************** ********** **************/ /* * irDetect function take measurements from IR sensor at pin irPin * and convert the measurement to distance in cm */ int irDetect(int irPin) { int sum = 0; // Initialize sum for 50 measurements for ( int i = 0; i < 50; i++ ) // Take 50 measurements to reduce error { sum += analogRead(irPin); delay(1); } int AN_in = sum / 50; // Take average of the 50 measurements float volt= AN_in * (5.0 / 1024.0); // Convert measurement to distance in cm if (volt > 3) { return 0; } else if (volt < 0.4) { return 100; } else { int distance = (int) 245.4*exp(-4.133*volt)+43.91*exp(-0.6349*volt); return distance; } }