# Need help on programming servomotor!

Hi,
I’m having a project in my electronic class and I need your help to code the rotation of my motor.
How can I change my code for the motor to rotate clockwise and anti clockwise depending on certain variables?

if (mode == 0) {
* if (cm1 <= 50) {*
* servomoteur.write(+60);*
* delay (1000);*
* }*
* if (cm1 > 50 && cm1 <= 150) {*
* servomoteur.write (+40);*
* delay (1000);*
* }*
* if (cm1 > 150 && cm1 <= 250) {*
* servomoteur.write(+20);*
* delay (1000);*
* }*
* if (cm1 > 250)*
* servomoteur.write (0);*
* delay (1000);*
* }*

* if (mode == 1) {*
* if (cm2 <= 50) {*
* servomoteur.write(-60);*
* delay (1000);*
* }*
* if (cm2 > 50 && cm1 <= 150) {*
* servomoteur.write (-40);*
* delay (1000);*
* }*
* if (cm2 > 150 && cm1 <= 250) {*
* servomoteur.write(-20);*
* delay (1000);*
* }*
* if (cm2 > 250)*
* servomoteur.write (0);*
* delay (1000);*

I’m using + and - for the angle of rotation of the motor (servomoteur.write(xx)) I don’t think it’s going to work and I would like to know if there’s any alternative ways to do so.

0 - 89 rotates the servo in one direction, and 91 - 180, the other. 90 is usually Zero or no direction.

You can use a map to set the correct values.

servo.Write(map(myVal, -60, 60, 0, 180));

tp_truong16:
Hi,
I’m having a project in my electronic class and I need your help to code the rotation of my motor.
How can I change my code for the motor to rotate clockwise and anti clockwise depending on certain variables?

``````if (mode == 0) {
``````

if (cm1 <= 50) {
servomoteur.write(+60);
delay (1000);
}
if (cm1 > 50 && cm1 <= 150) {
servomoteur.write (+40);
delay (1000);
}
if (cm1 > 150 && cm1 <= 250) {
servomoteur.write(+20);
delay (1000);
}
if (cm1 > 250)
servomoteur.write (0);
delay (1000);
}

if (mode == 1) {
if (cm2 <= 50) {
servomoteur.write(-60);
delay (1000);
}
if (cm2 > 50 && cm1 <= 150) {
servomoteur.write (-40);
delay (1000);
}
if (cm2 > 150 && cm1 <= 250) {
servomoteur.write(-20);
delay (1000);
}
if (cm2 > 250)
servomoteur.write (0);
delay (1000);

``````

I'm using + and - for the angle of rotation of the motor (servomoteur.write(xx)) I don't think it's going to work and I would like to know if there's any alternative ways to do so.

``````

Make mode = 1 for forward and -1 for reverse. Then your code can be shortened to:

``````    if (cm1 <= 50) {
myVal = mode * 60;
}
if (cm1 > 50 && cm1 <= 150) {
myVal = mode * 40;
}
if (cm1 > 150 && cm1 <= 250) {
myVal = mode * 20;
}
if (cm1 > 250)
myVal = 0;
}
servo.Write(map(myVal, -60, 60, 0, 180));
delay (1000);
``````