Ok. so i want to control a motor to move in a forward direction for 10 seconds and stop when triggered by an ultrasonic sensor. but the motor keeps moving after the delay and won't stop. like i want it to move in a forward direction then stop but it keeps moving even after the delay you get?
int trig = 9;
int echo = 8;
int in1 = 7;
int in2 = 6;
int duration = 0;
int distance = 0;
void setup()
{
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
digitalWrite(in1, HIGH);
digitalWrite(in2, HIGH);
Serial.begin(9600);
The motor rotates in the forward direction then pauses for a sec and keeps on rotating and vice versa when i bring a wall near the ultrasonic sensor you get?
What i want is for it to rotate for a sec then stop and vice versa when i bring a wall near the ultrasonic sensor
The way you have it programmed is if the distance is less than 10cm it will move forward for 1 second and if it is more than 10cm it will move in reverse for 1 second. It will do that over and over again. Is that what you want?
Read from a distance:
wait 1 second:
If the distance <= 10:
turn forward:
Rotate for a second:
Stop:
Read from a distance............
If the distance is greater than 10
turn back:
Rotate for a second:
Stop:
Read from a distance............
and it stays like this always...
OK. That is not hard but realize if you move forward and distance remains <=10 then the robot will be stuck. Also vice versa if you move in reverse and distance remains >10 then robot will be stuck.
This should work but I can't test right now. It will alternate between forward and reverse based on distance and stop flags. Like I said it leaves conditions where it can get stuck.
Read from a distance:
wait 1 second:
If the distance <= 10:
turn forward:
Rotate for a second:
Stop:
Read from a distance............
If the distance is still <=10
hold till distance is greater than 10
then
Read from a distance, if distance is greater than 10
move backwards
stop
hold till distance greater than 10
then move forward and so on