about DC motor control via IR sensor

I'm trying to control a DC motor via IR sensor.

no idea how to coding the source with under the conditions

please help me. :cry:

parts -

  1. arduino mega
  2. IR sensor
  3. L298n(motor driver)
  4. DC motor
  5. 12V power

current state = DC motor stop / IR sensor on

  1. IR sensor on - not detected - DC motor stop

  2. IR sensor detected - DC motor go forward (set time) - Stop - IR sensor no detected during (set time) -

DC motor reverse - Stop

  1. IR sensor detected - DC motor go forward (set time) - Stop - secondly, IR sensor detected -

DC motor reverse

Conditon 1.

during DC motor go forward(set time), IR sensor detected secondly -

DC motor reverse(as time go forward as) - Stop

another example

  1. - IR - detected - DC motor FW(4 sec) - Stop - IR sensor no detective untill (25sec) -

DC motor RV(4sec) - Stop

  1. IR - detected - during DC motor forwarding (2.5 sec) - IR sensor detected -

DC motor reversing(2.5 sec) - Stop

  1. - IR - detected - DC motor FW(4 sec) - Stop - (after 18sec) IR sensor detected -

DC motor reversing(4 sec) - Stop

i wrote the code which does not work what i want....

int Enable = 2;
int IR = 3;
int IR_status = 0;
int cnt=0;

// motor one
int enA = 10;
int a1 = 9;
int a2 = 8;
// motor two
int enB = 5;
int b1 = 7;
int b2 = 6;

void setup() {
pinMode(Enable, OUTPUT);
pinMode(IR, INPUT);
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(a1, OUTPUT);
pinMode(a2, OUTPUT);
pinMode(b1, OUTPUT);
pinMode(b2, OUTPUT);

}

void FW() { for(int i=0; i<100; i++){
analogWrite(enA,150); // Motor A
digitalWrite(a1,LOW);
digitalWrite(a2,HIGH);
analogWrite(enB,150); // Motor B
digitalWrite(b1,LOW);
digitalWrite(b2,HIGH);
}
}

void RV() {for(int i=0; i<100; i++){
analogWrite(enA,150); // Motor A
digitalWrite(a1,HIGH);
digitalWrite(a2,LOW);
analogWrite(enB,150); // Motor B
digitalWrite(b1,HIGH);
digitalWrite(b2,LOW);
}
}
void loop() {
digitalWrite(Enable,HIGH);
IR_status = digitalRead(IR);

if(IR_status){if(cnt==0)FW();}

if(cnt){if(--cnt==0)RV();}
}

i wrote the code which does not work what i want....

It does something. You didn't bother to explain what it does.
That somehow differs from what you want. You didn't bother to explain how it differs.

please help me.

How?

It may be useful for you to collaborate with the member who posted here. It seems you are both working on very similar projects.

  • Scotty