int E1 = 4; //Enable Right motor controller
int E2 = 8; //Enable Left motor controller
int M1 = 10; //Right Motor Forward PWM
int M2 = 5; //Left Motor Reverse PWM***********differential drive configuration
int highest_middle_x = 0; // The distance of the object from the center of the screen
int midx=0;
int left_threshold=0;
int right_threshold=0;
int i=0;// counter
int x = 0;
int StrArray[4] = {0, 0, 0, 0};//A buffer to store the ASCII value read in from the serial port
void setup()
{
pinMode(E1, OUTPUT);
pinMode(E2, OUTPUT);
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
Serial.begin(115200); // Open the serial port with a 9600 baud rate
Serial.println("Arduino Mega is ready"); // Print on screen
}
void loop()
{
// Wait for data to become available at the serial port
while(!Serial.available()){}
while(Serial.available())
{
StrArray[i] = Serial.read() - '0';
delay(1);
i++;
}
if(i==4)
x = StrArray[0]*1000 + StrArray[1]*100 + StrArray[2]*10 + StrArray[3];
if(i==3)
x = StrArray[0]*100 + StrArray[1]*10 + StrArray[2];
if(i==2)
x = StrArray[0]*10 + StrArray[1];
if(i==1)
x = StrArray[0];
i=0;
highest_middle_x = x;
delay(10);
Serial.println(highest_middle_x);
midx=320;
left_threshold= midx-50;
right_threshold= midx+50;
if (highest_middle_x <=left_threshold)
{
digitalWrite(E1,HIGH);
analogWrite (M1,200);
digitalWrite(E2,LOW);
analogWrite (M2,50);
delay(100);
}
else if (highest_middle_x >= right_threshold)
{
digitalWrite(E1,LOW);
analogWrite (M1,50);
digitalWrite(E2,HIGH);
analogWrite (M2,200);
delay(100);
}
else
{
digitalWrite(E1,HIGH);
analogWrite (M1,200);
digitalWrite(E2,HIGH);
analogWrite (M2,200);
delay(100);
}
}
|
|