Pages: [1]   Go Down
Author Topic: Convert angles to microseconds?  (Read 1296 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Full Member
***
Karma: 3
Posts: 221
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

Left Coast, CA (USA)
Offline Offline
Brattain Member
*****
Karma: 361
Posts: 17301
Measurement changes behavior
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Logged

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 220
Posts: 13846
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
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:
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:
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
Logged

Rob Tillaart

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

0
Offline Offline
Tesla Member
***
Karma: 145
Posts: 9675
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Pages: [1]   Go Up
Jump to: