#define trigPin 4
#define echoPin 3
#define motor 0
const byte RANGE_FAR = 60, RANGE_MED = 30, RANGE_CLOSE = 15,
SENS_HIGH = HIGH, SENS_MED = 200, SENS_LOW = 150;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motor, OUTPUT);
//ON Indicator:
digitalWrite(motor, HIGH);
delay(200);
digitalWrite(motor, LOW);
delay(100);
digitalWrite(motor, HIGH);
delay(200);
digitalWrite(motor, LOW);
delay(100);
}
void loop() {
//distance finding logic:
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" statement block for motor sensitivity:
if(distance<RANGE_CLOSE&&distance>0){
digitalWrite(motor,SENS_HIGH);
delay(100);
digitalWrite(motor,LOW);
}
else if(distance<RANGE_MED&&distance>=RANGE_CLOSE){
analogWrite(motor,SENS_MED);
delay(100);
digitalWrite(motor,LOW);
}
else if(distance>=RANGE_MED&&distance<RANGE_FAR){
analogWrite(motor,SENS_LOW);
delay(100);
digitalWrite(motor,LOW);
}
else
digitalWrite(motor,LOW);
}