// Sweep
// by BARRAGAN <http://barraganstudio.com>
// source circ 04 http://ardx.org/src//guide/2/ARDX-EG-OOML-WEB.pdf
//
// ping sonar source http://www.funnyrobotics.com/2011/03/arduino-with-parallax-ping-sensor.html
// GOAL: place sonar ping inside FOR statement of servo
// SERVO init
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
// SONAR Ping init
int PingPin = 7; // pin used for the Ping Sensor
int BaudRate = 9600; // Baud rate
void setup() {
myservo.attach(9); // SERVO: attaches the servo on pin 9 to the servo object
Serial.begin(BaudRate); // SONAR: Setup Serial
}
void loop() {
for(pos = 0; pos < 180; pos += 1) { // SERVO: goes from 0 degrees to 180 degrees in 1 degree steps
myservo.write(pos); // SERVO: tell servo to go to position in variable 'pos'
delay(15); // SERVO: waits ms for the servo to reach the position
serial.println(pos); // SERVO: print pos
pinMode(PingPin, OUTPUT); // SONAR: pin output
digitalWrite(PingPin, LOW); // SONAR: null
delayMicroseconds(2); // SONAR: null duration
digitalWrite(PingPin, HIGH); // SONAR: pulse
delayMicroseconds(5); // SONAR: pulse duration
digitalWrite(PingPin, LOW); // SONAR: null
pinMode(PingPin, INPUT); // SONAR: pin input, listen
unsigned long Duration = pulseIn(PingPin, HIGH); // SONAR: time how long the pin
// stays in HIGH state, sound input
if (Duration == 0) {
Serial.println ("No Pulse received from the sensor");
}
else {
Serial.println(Duration); // SONAR: print sound duration
Serial.print("Distance : ");
Serial.print(Convert_Time_Space(Duration)); // SONAR: convert the duration into distance
Serial.println (" cm");
}
delay (1000);
}
for(pos = 180; pos >= 1; pos -=1 ) { // SERVO: goes from 180 degrees to 0 degrees
myservo.write(pos); // SERVO: tell servo to go to position in variable 'pos'
delay(15); // SERVO: waits ms for the servo to reach the position
serial.println(pos); // SERVO: print pos
pinMode(PingPin, OUTPUT); // SONAR: pin output
digitalWrite(PingPin, LOW); // SONAR: null
delayMicroseconds(2); // SONAR: null duration
digitalWrite(PingPin, HIGH); // SONAR: pulse
delayMicroseconds(5); // SONAR: pulse duration
digitalWrite(PingPin, LOW); // SONAR: null
pinMode(PingPin, INPUT); // SONAR: pin input, listen
unsigned long Duration = pulseIn(PingPin, HIGH); // SONAR: time how long the pin stays
// in HIGH state, sound input
if (Duration == 0) {
Serial.println ("No Pulse received from the sensor");
}
else {
Serial.println(Duration); // SONAR: print sound duration
Serial.print("Distance : ");
Serial.print(Convert_Time_Space(Duration)); // SONAR: convert the duration into distance
Serial.println (" cm");
}
delay (1000);
}
unsigned long Convert_Time_Space(const unsigned long fnDuration ) {
return fnDuration / 29 / 2 ; // SONAR: converts time to distance 29 microseconds per cm.
}
}