## how to make my mbed car move and count even and odd for the servo to move up and down. thanks

1. include "mbed.h"
2. include "Servo.h"
3. include "Motor.h"
4. include "QEI.h"

Servo myservo(p23);

Motor R(p22,p5,p6);

Motor L(p21,p7,p8);

DigitalIn DFL(p11);

DigitalIn DFR(p12);

DigitalIn BUT(p13);

DigitalIn FRM(p18);

DigitalOut myled(LED1),myled2(LED2);

QEI Lwheel (p9,p30, NC , 48,QEI :: X4_ENCODING);

QEI Rwheel (p29,p10, NC , 48,QEI :: X4_ENCODING);

int y=0;

void followline()

{

if(DFL == 1 && DFR == 1)

{

R.speed(0.5);

L.speed(0.5); }

else if(DFL == 0 && DFR == 1)

{

L.speed(0);

R.speed(0.5);

}

else if(DFL == 1 && DFR == 0)

{

L.speed(0.5);

R.speed(0); }

else if(DFL == 0 && DFR == 0)

{

R.speed(0.5);

L.speed(0.5);

}

}

int main()

{

for(y=0;y<10;y++)

{

followline();

if ((FRM == 0) && (y % 2))

{ myled=1

R.speed (0);

L.speed (0);

wait(0.2);

myservo = 0;

y=y+1;

followline();

}

if ((FRM == 0) && (( y % 2)== 0))

{

myled2 = 1;

R.speed (0);

L.speed (0);

wait(0.2);

myservo = 0.5;

y=y+1;

followline();

}

else

{

followline();

}

}

}

##### 5 years, 4 months ago.

Firstly please use `<<code>>` and `<</code>>` when posting code (see the editing tips for details). Without it formatting gets lots and it's hard to tell the difference between comments and code.

Here's your code with a couple of tidy ups to remove duplicate lines and simplify the logic, functionally there is only one minor difference detailed below.

```#include "mbed.h"
#include "Servo.h"
#include "Motor.h"
#include "QEI.h"

Servo myservo(p23);
Motor R(p22,p5,p6);
Motor L(p21,p7,p8);

DigitalIn DFL(p11);
DigitalIn DFR(p12);

DigitalIn BUT(p13);
DigitalIn FRM(p18);

DigitalOut myled(LED1),myled2(LED2);

QEI Lwheel (p9,p30, NC , 48,QEI :: X4_ENCODING);
QEI Rwheel (p29,p10, NC , 48,QEI :: X4_ENCODING);

int y=0;

void followline() {
// simplified from your version, rather than checking exact values do a comparison between the two.
if (DFR > DFL) {
L.speed(0);
R.speed(0.5);
} else if (DFL > DFR) {
L.speed(0.5);
R.speed(0);
} else {
R.speed(0.5);
L.speed(0.5);
}
}

int main() {

for(y=0;y<10;y++) {
followline();

if (FRM == 0) { // both if's were identical other than one line so combine them
myled=1; // you missed the ; on this in the first if.
R.speed (0);
L.speed (0);

wait(0.2);
if (y%2)                    // this was the difference between the two.
myservo = 0;
else
myservo = 0.5;

y=y+1;
}
followline(); // every path through the if statement ended wit h this so moved outside the if
}
}
```