CODE:-
int motorspeedpin1=5;
int motorspeedpin2=9;
int dirt1=2;
int dirt2=3;
int dirt3=7;
int dirt4=8;
int myspeed=255;
int wait=100;
int trigpin=12;
int echopin=11;
int traveltime;
int targetdistance;
void setup() {
// put your setup code here, to run once:
pinMode(motorspeedpin1,OUTPUT);
pinMode(dirt1,OUTPUT);
pinMode(dirt2,OUTPUT);
pinMode(motorspeedpin2,OUTPUT);
pinMode(dirt3,OUTPUT);
pinMode(dirt4,OUTPUT);
pinMode(trigpin,OUTPUT);
pinMode(echopin,INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigpin,LOW);
delayMicroseconds(10);
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);
delayMicroseconds(25);
traveltime=pulseIn(echopin,HIGH);
targetdistance=(traveltime*0.034)/2;
Serial.println(targetdistance);
if (targetdistance>9) {
digitalWrite(dirt1,HIGH);
digitalWrite(dirt2,LOW);
analogWrite(motorspeedpin1,myspeed);
digitalWrite(dirt3,HIGH);
digitalWrite(dirt4,LOW);
analogWrite(motorspeedpin2,myspeed);
}
if (targetdistance<10) {
digitalWrite(dirt1,LOW);
digitalWrite(dirt2,LOW);
digitalWrite(dirt3,LOW);
digitalWrite(dirt4,LOW);
delay(200);
digitalWrite(dirt1,LOW);
digitalWrite(dirt2,HIGH);
analogWrite(motorspeedpin1,myspeed);
digitalWrite(dirt3,LOW);
digitalWrite(dirt4,HIGH);
analogWrite(motorspeedpin2,myspeed);
delay(500);
digitalWrite(dirt1,HIGH);
digitalWrite(dirt2,LOW);
analogWrite(motorspeedpin1,myspeed);
digitalWrite(dirt3,LOW);
digitalWrite(dirt4,LOW);
delay(500);
}
}
0 Comments