Arduino Distance Sensor Script

ultrasonic-sensorYou can buy the 4-leg sensor shield that is compatible with Arduino, to detect and measure the distance of any obstacles that may block your Arduino car.

 

For connecting to your existing Raspberry Internet Rover, you can find any 2 spares of the pins. This examples uses 12 (trigger), 13 (echo), voltage (+) and ground (-) pins.

 

/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
More info at: http://goo.gl/kJ8Gl
*/

#define trigPin 13
#define echoPin 12

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);  // Added this line
delayMicroseconds(2); // Added this line

digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); – Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println(“Out of range”);
}
else {
Serial.print(distance);
Serial.println(” cm”);
}
delay(500);
}

The above is a very complete script which you can include in your robot project. Please follow Raspberry Internet Rover tutorial.

 [post_view]

(Visited 1,988 times, 1 visits today)