Sine and Cosine in C++

Hey i’m one of the programmers from team 245 the Adambots and we are trying to use the gyro and accelerometer together to determine distances traveled with our robot.

Since we are not expert programmers, we are wondering how to use sin and cos to find distances traveled using vectors.

Note: we just need the syntax for the use of these functions.

float x=sin(radian);
float y=cos(radian);
from
www.cplusplus.com/reference/clibrary/cmath/sin/
and
www.cplusplus.com/reference/clibrary/cmath/cos/

*note: you may need to #include <math.h>

you absolutely have to import math.h, unless you’re using gnulibc which has math.h byitself

Or you can use the C++ wrapper for math.h and do
#include <cmath>

We used the accelerometer to determine the distance travelled by doing a double integration on acceleration. We wrote a generic accelerometer module that will give you accel/vel/distance on all three axes. Then we defined a macro called MAGNITUDE that will take the x and y vectors and gives you distance magnitude and also the macro DIR_DEGREE to calculate the heading.


#define MAGNITUDE(x,y)          sqrt(pow(x, 2) + pow(y, 2))
#define RADIANS_TO_DEGREES(n)   ((n)*180.0/PI)
// Forward is 0-radian
#define DIR_RADIANS(x,y)        (((x == 0.0) && (y == 0.0))? 0.0: atan2(x, y))
#define DIR_DEGREES(x,y)        RADIANS_TO_DEGREES(DIR_RADIANS(x, y))

Our accelerometer code can be found at
http://proj.titanrobotics.net/hg/Frc/2010/code/file/e44126e46aee/inc/TrcAccel.h

But be careful when using the double integrator code. The accelerometer has noise, so even if the robot sits still, you may end up with an increasing velocity if you sit long enough. Our code doesn’t enable the accelerometer integration until right before we need it. And it clears the integrator right before we enable it so it clears the cumulated error. It also does zero-G calibration at the beginning initialization phase to eliminate the DC offset of the accelerometer. Also be mindful on situation that if your robot gets bumped or accelerates/decelerates too fast, it could saturate the accelerometer output so to give you error on your integraton. With all those limitations in mind, it will give you decent results for a short period of time.

Does your code try to do anything to compensate for gravity when going over the bumps?

~

No, our code was primarily used for autonomous period. And we did not plan to go over the bump. Like I said, if you hit the bump, the impact will probably saturate the accelerometer and render the reading inaccurate. We know the limitation of the code and only use it within its limit. In any case, the accelerometer library code will give you the accel/vel/distance for all the axes. So in theory, you could take the z-axis data and do some compensation with it. But we did not do that in our main code.