 # Convert angles to microseconds?

How do I convert angles to microseconds? I know that 1000ms = 0 degrees, 1500ms = 90 degrees, and 2000ms = 180 degrees. What about 60 degrees and 120 degrees?

jeffmorris: How do I convert angles to microseconds? I know that 1000ms = 0 degrees, 1500ms = 90 degrees, and 2000ms = 180 degrees. What about 60 degrees and 120 degrees?

Well you could use the map command.

microValue = map(angleDegrees, 0,180,1000,2000);

Lefty

The map function will do well but might have some (small) error as it uses integer math which does rounding.

90 degrees is a step of 500. so 9 degrees is a step of 50. we can not simplify this in integer space, without rounding errors. we know 0.9 is a step of 5.

so we can do a float function

``````float degree2ms(float degrees)
{
return 1000.0 + degrees * 50.0/9.0;
}
``````

if we want no float math we can multiply the degrees by an integer const and divide the result at the end.

``````unsigned int degree2ms(unsigned int degrees)
{
unsigned int rv = degrees * 3; // 0..1080
rv = rv * 50;  // 0..54000
rv = rv /9;  // 0..6000
rv = rv /3;  // 0..200
return 1000 + rv;
}
``````

This can be rewritten to a oneliner

``````unsigned int degree2ms(unsigned int degrees)
{
return  1000 + degrees * 150 / 27;
}
``````

to minimize the rounding error of integer math we can add a rounding factor [which is half of the divider].

``````unsigned int degree2ms(unsigned int degrees)
{
return  1000 + (degrees * 150  + 13) / 27;
}
``````

filling in 60 --> 1333 120 --> 1667 0 --> 1000 180 --> 2000 1 --> 1006 179 --> 1994

I think the servo library maps degree values to microsecond values, so some tweeking might be done there.