Arduino Forum

Topics => Robotics => Topic started by: jeffmorris on Nov 17, 2012, 11:53 am

Title: Convert angles to microseconds?
Post by: jeffmorris on Nov 17, 2012, 11:53 am
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?
Title: Re: Convert angles to microseconds?
Post by: retrolefty on Nov 17, 2012, 11:57 am

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

Title: Re: Convert angles to microseconds?
Post by: robtillaart on Nov 17, 2012, 02:00 pm
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

Code: [Select]
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.

Code: [Select]

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
Code: [Select]

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].
Code: [Select]

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
Title: Re: Convert angles to microseconds?
Post by: zoomkat on Nov 17, 2012, 06:26 pm
I think the servo library maps degree values to microsecond values, so some tweeking might be done there.