i want to get the coordinates X and Y using a simple code, but as i have used if condition my code increments the counter only once the key is pressed. i want the counter to be updated every 50ms until any other key is pressed. i have used two counters Xdir and Ydir.
my code is as follows:-
char INBYTE;
int Lmotor1 = 3; // LED on pin 13
int Lmotor2=7;
int Rmotor1=4;
int Rmotor2=8;
int Xdir=0;
int Ydir=0;
void setup() {
Serial.begin(9600);
pinMode(Lmotor1, OUTPUT); pinMode(Lmotor2, OUTPUT); pinMode(Rmotor1, OUTPUT); pinMode(Rmotor2, OUTPUT);
delay (200);
}
void forward()
{digitalWrite(Lmotor1, HIGH);
digitalWrite(Rmotor1, LOW);
digitalWrite(Lmotor2, HIGH);
digitalWrite(Rmotor2, LOW);
delay(50);
Ydir++;}
void backward()
{digitalWrite(Lmotor1, LOW);
digitalWrite(Rmotor1, HIGH);
digitalWrite(Lmotor2, LOW);
digitalWrite(Rmotor2, HIGH);
delay(50);
Ydir--;}
void left ()
{digitalWrite(Lmotor1, LOW);
digitalWrite(Rmotor1, HIGH);
digitalWrite(Lmotor2, HIGH);
digitalWrite(Rmotor2, LOW);
delay(50);
Xdir--;}
void right()
{digitalWrite(Lmotor1, HIGH);
digitalWrite(Rmotor1, LOW);
digitalWrite(Lmotor2, LOW);
digitalWrite(Rmotor2, HIGH);
delay(50);
Xdir++;}
void pause(){digitalWrite(Lmotor1, LOW);
digitalWrite(Rmotor1, LOW);
digitalWrite(Lmotor2, LOW);
digitalWrite(Rmotor2, LOW);
}
void loop() {
Serial.println("Press 1 to go ahead press2 to backward press 3 to move left press 4 to move right");
while (!Serial.available()); // stay here so long as COM port is empty
INBYTE = Serial.read(); // read next available byte
if( INBYTE == '1' ) {
forward(); }
if( INBYTE == '2' )
{ backward();
}
if( INBYTE == '3' )
{ left();}
if( INBYTE == '4' )
{ right();}
if( INBYTE == '5' )
{ pause();
Serial.print("X coordinate:");
Serial.println(Xdir);
Serial.print("Y coordinate:");
Serial.println(Ydir);
}}