Logic:Making the motor vibrate more when obstacle is closer..
The following program :some doubts in it:
#define trigPin 12
#define echoPin 11
#define motorPin 3
void setup() {
Serial.begin (9600);
pinMode(echoPin,INPUT);
pinMode(trigPin,OUTPUT);
}
void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000); //WHAT DOES IT DO..waits for 1ms..rite? but when we
** //trigger the sensor hc sr04 we first give a low signal of 2uS and then**
** // 10uS High pulse and then a low signal** .will this logic also gonna
//work..as its not working sometimes with my program..
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance <400 && distance >300)
{
analogWrite(motorPin,0);
Serial.print("Out of range");// here in the serial monitor..it prints the distance of 6/14 cm repeatedly
// even if the obstacle is out of range.and sometimes displays out of range
// which is the desired result
Serial.println(" ");
}
else if (distance <=300 && distance >250)
{
analogWrite(motorPin,50);
}
else if (distance <=250 && distance >200)
{
analogWrite(motorPin,100);
}
else if (distance <=200 && distance >150)
{
analogWrite(motorPin,145);
}
else if (distance <=150 && distance >100)
{
analogWrite(motorPin,190);
}
else if (distance <=100 && distance >80)
{
analogWrite(motorPin,205);
}
else if (distance <=80 && distance >10)
{
analogWrite(motorPin,240);
}
else
{
analogWrite(motorPin,255);
}
Serial.print(distance);
Serial.println(" cm");
delay(500);
}