Go Down

Topic: Convert angles to microseconds? (Read 1 time) previous topic - next topic

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?

retrolefty


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


robtillaart

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
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

zoomkat

I think the servo library maps degree values to microsecond values, so some tweeking might be done there.
Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   8)

Go Up