Arduino Code:
#include <Servo.h>
#include <SoftwareSerial.h>
// Defines Tirg and Echo pins of the Ultrasonic Sensor
const int Trig_pin = 7; // Triggers Pulsoe for Ultrasonic Sensor
const int Echo_pin= 12; // Recevies Echo for Ultrasonic Sensor
int ledpin = 13; // led pin command pin
int buzzarpin=4;
// Variables for the duration and the distance
long duration; // distance value for ultrasonic
int distance;
Servo Rishi; // Servo motor that controls
void setup() {
Serial.begin(9600); // Set up Serial library at 9600 bps
Rishi.attach(9); // Servo motor is attached to pin 9
pinMode(Trig_pin, OUTPUT); // initialize the pulse pin as output:
pinMode(Echo_pin, INPUT);// initialize the echo_pin pin as an input:
pinMode(ledpin,OUTPUT);
pinMode(buzzarpin,OUTPUT);
}
void loop()
{
// rotates the servo motor from 10 to 178 degrees
for(int i=0;i<=180;i++)
{
Rishi.write(i);
delay(50);
distance = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree
Serial.print(i); // Sends the current degree into the Serial Port
Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
Serial.print(distance); // Sends the distance value into the Serial Port
Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
Sensor ();
while (distance > 5 && distance < 40)
{ // if sensor detects something to close
delayMicroseconds(50); //pauses servo
digitalWrite(ledpin,HIGH); // turns on led
digitalWrite(buzzarpin,HIGH);
Sensor(); // checks if object is still to close
}
digitalWrite(ledpin,LOW); // turns off led
digitalWrite(buzzarpin,LOW);
}
for(int i=180;i>0;i--)
{
Rishi.write(i);
delay(50);
distance = calculateDistance();
Serial.print(i);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
Sensor ();
while (distance > 5 && distance < 40) {
delayMicroseconds(50);
digitalWrite(ledpin,HIGH);
digitalWrite(buzzarpin,HIGH);
Sensor();
}
digitalWrite(ledpin,LOW);
digitalWrite(buzzarpin,LOW);
}
}
void Sensor() { // checks distance from sensor to nearest object straight ahead
digitalWrite(Trig_pin, LOW);
delayMicroseconds(2); // delays
digitalWrite(Trig_pin, HIGH); //starts signal
delayMicroseconds(5); // delay
digitalWrite(Trig_pin, LOW); //stops signal
duration = pulseIn(Echo_pin,HIGH); // checks what the value is
distance=duration*0.034/2;
}
// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance()
{
digitalWrite(Trig_pin, LOW);
delayMicroseconds(2);
digitalWrite(Trig_pin, HIGH);
delayMicroseconds(5);
digitalWrite(Trig_pin, LOW);
duration = pulseIn(Echo_pin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance= duration*0.034/2;
return distance;
}