1

Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to +180 when joy is forward or back.

I just cant seem to figure out the mapping or setup for the code for this part. I remember seeing it done before but my google skils are failing me and i cant seem to find it again. Thanks

hendr13x
  • 11
  • 3

2 Answers2

2

Try this one although, the others answered you properly :

#include <Servo.h>
Servo myservo;
int potpin = 1;
int val;

void setup () { myservo.attach(9); }

void loop () { val = analogRead(potpin); val = map(val, 0, 1023, 0, 360); myservo.write(val); delay(20); }

Connect the signal wire of your Servomotor to PWM pin number 9 of Arduino Connect the output of your joystick to A1 pin of your arduino

Actually i'm not sure about one of that lines and i forgot the correct form, if didn't work, change this line :

val = map(val, 0, 1023, 0, 360);

To this :

val = map(val, 0, 1023, -180, 180);

I think both of them works

Good luck

Curious guy
  • 113
  • 10
1

You can use the map function, see Arduino Map Function.

So in your case, assuming a value of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get

int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).

UPDATE

It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).

For this you need two maps depending on the value:

int mappedValue = 0;
if (value < 512) // Backwards
{
    mappedValue = map(value, 0, 511, 180, 0);
}
else // Forward
{
    mappedValue = map(value, 512, 1023, 0, 180);
}
Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58