I want to build a project that uses proximity sensors to reverse the direction of the DC motors. There are 2 proximity sensors that decide the motor direction. I want proximity sensor that detects the metal and reverses the direction of motor once it reaches the other end it is again detected by the proximity sensor 2 and again the direction is reversed. I want to create a loop for this and want it to run only for three times and then stop. My code is given below, with this code i can only reverse the direction of motor but cannot put it in loop and execute it only three times. So, guys I need your help regarding this. Thanks in advance.
P.S. The sensors are inductive type proximity sensors.
float metalDetected1; // Proximity sensor 1
float metalDetected2; // Proximity sensor 2
int monitoring1; //
int monitoring2;
int metalDetection1 = 0; // Assigning digital port 0 to sensor 1
int metalDetection2 = 1; // Assigning digital port 1 to sensor 2
int motor_left[] = {2, 3}; // Assigning analog port 2 and 3 to motor 1
int motor_right[] = {7, 8}; // Assigning analog port 7 and 8 to motor 2
void setup()
{
Serial.begin(9600);
int i; // Setup motors
for(i = 0; i < 2; i++)
{
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
}
}
void loop()
{
monitoring1 = analogRead(metalDetection1); // Read the monitoring 1 value
monitoring2 = analogRead(metalDetection2); // Read the monitoring 2 value
metalDetected1 = (float) monitoring1*100/1024.0;
metalDetected2 = (float) monitoring2*100/1024.0;
Serial.print("14CORE METAL DETECTOR TEST");
Serial.print("Initializing Proximity Sensor");
Serial.print("Please wait...");
Serial.print("Metal 1 is Proximited = "); // Sensing the proximity and displaying for sesnsor 1
Serial.print(metalDetected1);
Serial.println("%");
Serial.print("Metal 2 is Proximited = "); // Sensing the proximity and displaying for sesnsor 2
Serial.print(metalDetected2);
Serial.println("%");
if (monitoring1 < 250)
{
drive_forward();
}
if (monitoring2 < 250)
{
drive_backward();
}
}
void drive_forward(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);
digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}
void drive_backward(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);
digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}