how can my code be fixed to make the ultrasonic sensor control the DC motor based on the distance it measures? So that i

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

how can my code be fixed to make the ultrasonic sensor control the DC motor based on the distance it measures? So that i

Post by answerhappygod »

how can my code be fixed to make the ultrasonic sensor control
the DC motor based on the distance it measures?
So that it can function like in this
video:
How Can My Code Be Fixed To Make The Ultrasonic Sensor Control The Dc Motor Based On The Distance It Measures So That I 1
How Can My Code Be Fixed To Make The Ultrasonic Sensor Control The Dc Motor Based On The Distance It Measures So That I 1 (48.21 KiB) Viewed 42 times
int trig = D5; // Initialize pin D5 as HC-SR04 trigger pin
int echo = D4;// Initialize pin D5 as HC-SR04 Echo pin
int motorPin1 = D10; //Initialize pin D10 to drive motor1
int motorPin2 = D11;//Initialize pin D11 to drive motor1
int led2 = D3;//green led
int led1 = D12;// red led
int duration = 0;
int distance = 0;
void setup()
{
pinMode(trig , OUTPUT);
pinMode(echo , INPUT);
pinMode(led1, OUTPUT);
pinMode(led2 , OUTPUT);
pinMode(motorPin1 , OUTPUT);
pinMode(motorPin2 , OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trig , HIGH);
delayMicroseconds(1000);
digitalWrite(trig , LOW);
duration = pulseIn(echo , HIGH);
distance = (duration / 2) / 28.5 ;// calculate distance in
CM
//Serial.println(distance);
if ( distance < 20 ) {
Serial.print(distance);
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2 , LOW);
digitalWrite(led1 , HIGH);
digitalWrite(led2 , LOW);
Serial.println("cm MOTOR STOP");
delay(1000);
}
else {
Serial.print(distance);
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2 , LOW);
digitalWrite(led1 , LOW);
digitalWrite(led2 , HIGH);
Serial.println("cm MOTOR START");
delay(1000);
}
}
I will give a thumbs
up!!!
L2930 HC-SR04 9V DIGITAL PWM O UNO ARDUINO POWER ANALOG IN 222
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply