Decide if motor needs to turn left or right

Hello Everybody,

I am looking for someone who can help me with a piece of code.
The plan is to connect a real aviation compass (HSI) to a sim through a Arduino.
Basically the compass is a motor with a position sensor.
The position sensor and the simulator will provide a compass heading (0 to 360 degrees) to the Arduino.

The problem is, I don't know how to let the Arduino decide if the motor has to turn left or right to get to the correct heading the fastest.

for example:
If the current heading is 0 and the simulator tells the Arduino to go to 90 degrees.
the motor has to turn counter clockwise until to new value is reached.

and if the current heading is at 0 and the sim tells the Arduino to go to 270 degrees.
the motor needs to turn clockwise until to new value is reached.

Anybody an idea how to accomplish this?
thanks all in advance,

Bob

Subtract the current heading from the desired heading. If the difference is more than 180 go one way to the closest if greater than 180 go the other way.

If you are at 0 and want to go to 90 that is less than 180 so go 90 CW. To go from 0 to 270, that is more than 180 so go 90 CCW to get to 270.

consider
(corrected)

    hdg   targ  delta
    -90    -90      0
    -90    -45     45 right
    -90      0     90 right
    -90     45    135 right
    -90     90    180 right
    -45    -90    -45 left
    -45    -45      0
    -45      0     45 right
    -45     45     90 right
    -45     90    135 right
      0    -90    -90 left
      0    -45    -45 left
      0      0      0
      0     45     45 right
      0     90     90 right
     45    -90   -135 left
     45    -45    -90 left
     45      0    -45 left
     45     45      0
     45     90     45 right
     90    -90   -180 left
     90    -45   -135 left
     90      0    -90 left
     90     45    -45 left
     90     90      0
awk '
BEGIN {
    printf " %6s %6s %6s\n", "hdg", "targ", "delta"
    dA = 45
    a0 = -180
    a1 =  180
    for (hdg = a0; hdg <= a1; hdg += dA)
        for (targ = a0; targ <= a1; targ += dA)  {
            delta = targ - hdg
            if (180 < delta)
                delta -= 360
            else if (-180 > delta)
                delta += 360
            printf " %6d", hdg
            printf " %6d", targ
            printf " %6d", delta
            if (0 < delta)
                printf " right"
            else if (0 > delta)
                printf " left"
            printf "\n"
        }
}'

@bobj61
Wouldn't it be easier to use a Arduino compass module??

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.