#define trigPin 13
#define echoPin 12
#define led 22
#define led2 23
void setup()
{
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop()
{
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 50) // If a object is within 50cm of the sensor, the motor will isolate.
{
digitalWrite(led,HIGH); // The red LED will go HIGH when the motor is isolated
digitalWrite(led2,LOW); // The green LED will go LOW when the motor is isolated - This LED is actually connected to a mechanical relay, driving a DC motor.
Serial.println("Obstruction, DC motor isolated");
delay(2000);
}
else
{
digitalWrite(led,LOW); // Roles reversed if object is further than 50cm
digitalWrite(led2,HIGH);
Serial.println("Motor Running");
Serial.print(distance);
Serial.println(" RPM");
delay(2000);
}
{
}
}