Hello,
I am working on a project where I need to measure the angle of inclination for a solar panel mounting system. The panels will start at an angle of 0 and will need to measure all the way to 90 degrees. I have already found some code others have used for similar projects and have modified it a bit, but I am having issues displaying the correct angle to the serial monitor. For example when it should measure 0 degrees it outputs a negative angle and when it should display 90 degrees it measures about 70ish.
The sensor will only be allowed to move in one direction, specifically in the Xm direction as the attached image shows.
Here is the code:
#include <math.h>
int xPin = 2; // X input from accelerometer
int yPin = 3; // Y input accelerometer
int Xraw, Yraw;
double xGForce, yGForce, Xangle, Yangle;
void setup() {
Serial.begin(9600);
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
Serial.print("Welcome to the Earthlab!");
Serial.println();
Serial.println();
delay(2000);
}
void loop() {
// read x and y values..pulseIn returns length of pulse
//in microseconds or zero if no complete pulse was received
Xraw = pulseIn(xPin,HIGH);
Yraw = pulseIn(yPin,HIGH);
//Due to erroneous output of pulseIn();
// when x and y are calculated together
// pulseIn(); must be used twice.
Xraw = pulseIn(xPin,HIGH);
Yraw = pulseIn(yPin,HIGH);
//Calculate G-force in milli g's
xGForce = ((Xraw / 10) - 500) * 8;
// yGForce = ((Yraw / 10) - 500) * 8;
// Calculate angle (radians) for both -x and -y axis.
Xangle = asin( xGForce / 1000.0 );
//Yangle = asin ( yGForce / 1000.0 );
// Convert radians to degrees.
Xangle = Xangle * (360 / (2*M_PI));
//Yangle = Yangle * (360 / (2*M_PI));
Serial.print("The current angle of inclination is ");
//Force angle to 0 if there is any negative value
if(Xangle<0)
{
Xangle = 0;
}
// Print the angle with printDouble function
printDouble (Xangle, 10);
delay(500);
}
void printDouble( double val, unsigned int precision)
{
Serial.print(int(val));
Serial.print(".");
unsigned int frac;
if(val >= 0)
{
frac = (val - int(val)) * precision;
}
else
frac = (int(val) - val ) * precision;
int frac1 = frac;
while(frac1 /= 10)
{
precision /= 10;
}
precision /= 10;
while( precision /= 10)
{
Serial.print("0");
}
Serial.print(frac, DEC);
Serial.print(" degrees");
Serial.println();
Serial.println();
}
Any help would be greatly appreciated!