This code we are using only one motor and one hc-sr04 ultrasonic sensor, the code is shown below:
#define trigPin 7
#define echoPin 6
#define motorPin 5
void setup()
{
Serial.begin(9600);// to use the serial monitor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motorPin, OUTPUT);
}
void loop()
{
int duration,distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2)/29.1;
Serial.print(distance);//to print the distance on the serial monitor
Serial.println("cm");
// to make the motor vibrate depending on the distance
// if the ultrasonic sensor is too far from the obstacle it will vibrate slowly
// if the ultrasonic sensor is very close to the obstacle it will vibrate very fast
if(distance <= 60 && distance >= 45)
{
// to make the motor vibrate
digitalWrite(motorPin, HIGH); // making the motor on
delay(200);
digitalWrite(motorPin, LOW);// making the motor off
delay(200);
}
else if(distance < 45 && distance >= 30)
{
digitalWrite(motorPin, HIGH);
delay(100);
digitalWrite(motorPin, LOW);
delay(100);
}
else if(distance < 30){
digitalWrite(motorPin, HIGH);
delay(50);
digitalWrite(motorPin, LOW);
delay(50);
}
else
{
digitalWrite(motorPin, LOW);
}
}
We want you to tell us your comment about the code.
And we want to add two more motors and two ultrasonic sensors, one of them in the left and the other in the right.
We want you to help us in the code, because we don't know how we can change it for two other motors.
We want you to help us in the code
isn't really a question.