String ms;
int a,b;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(8, INPUT);
pinMode(9, OUTPUT);
digitalWrite(9, LOW);
digitalWrite(8, LOW);
}
void loop() {
long duration,cm ;
// SEND ECHO
digitalWrite(9, HIGH);
delayMicroseconds(5);
digitalWrite(9, LOW);
delayMicroseconds(5);
// CALCULATE DISTANCE
duration = pulseIn(8, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
if(cm>15){
// Forward
digitalWrite(2,LOW);
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
}
if(cm<15){
// Reverse
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
}
if(cm<15&cm>10){
// Right
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(1000);
}
if(cm<10){
// stop
digitalWrite(2,LOW);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
}
}
long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
No comments:
Post a Comment