Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Ping))) Sensor
- This sketch reads a PING))) ultrasonic rangefinder and returns the
- distance to the closest object in range. To do this, it sends a pulse
- to the sensor to initiate a reading, then listens for a pulse
- to return. The length of the returning pulse is proportional to
- the distance of the object from the sensor.
- The circuit:
- * +V connection of the PING))) attached to +5V
- * GND connection of the PING))) attached to ground
- * SIG connection of the PING))) attached to digital pin 2
- http://www.arduino.cc/en/Tutorial/Ping
- created 3 Nov 2008
- by David A. Mellis
- modified 30 Jun 2009
- by Tom Igoe
- modified Nov 2010
- by Joe Saavedra
- Modified 29 March 2015
- by Nebiyu Tadesse
- */
- #include <Servo.h>
- /* Ping distance measurement - global variables */
- int pingPin = 2; //the pin the ping is attached to (change it to whichever you're plugging it to)
- long int duration, distanceInches;
- int val = 0;
- long distanceFront=0; //cm
- Servo myservo; //state your servo
- long distanceCm()
- {
- pinMode(pingPin, OUTPUT); //set the ping sensor as output
- digitalWrite(pingPin, LOW); //just to be careful of the values
- delayMicroseconds(2); // wait 2 microsecond
- digitalWrite(pingPin, HIGH); //send pulses for 5 microsecond
- delayMicroseconds(5);
- digitalWrite(pingPin, LOW); //set the ping sensor low
- pinMode(pingPin, INPUT); //set the ping sensor as input to get the readings
- duration = pulseIn(pingPin, HIGH); //the duration is the pulse that came back when the ping was one
- distanceInches = microsecondsToInches(duration); // result from calculations
- return microsecondsToCentimeters(duration); // result from calculations
- }
- long microsecondsToInches(long microseconds)
- {
- return microseconds / 74 / 2; //The calculation to get the microsecond and change it to inches
- }
- long microsecondsToCentimeters(long microseconds)
- {
- return microseconds / 29 / 2; //the calculations to get the microsecond and change it to centimeters
- }
- void setup()
- {
- myservo.attach(8); //the pin the servo is attached to (change the to whichever your pin is attached to)
- }
- void loop()
- {
- val = distanceCm();
- if (val > 1){ // Filters out any stray 0.00 error readings
- if (val <= 180) { // The sensor can bring a reading more than 180, but the servo can't go higher than 180
- myservo.write(val); //move the servo to the same value as the ping sensor
- }
- else
- {
- myservo.write(180); //no need for this. Only if you want the servo to stay at 180 is the ping sensor get higher than 180
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement