Firstly, I want to say hello, as I'm newbie on this forum.
I'm working on my first arduino project which is self-balancing one axis swing.
Here is what I want from code :
In first void loop run, I have 'new_angle' variable which is first mesurement of current angle.
Then, this angle is being saved in other variable named 'old_angle'.
In following void loop runs I want to have 'new_angle, being actualised, while old_angle would have the value of new_angle from previous runs. So that I can calculate angle difference in time (acceleration).
The problem is, that old_angle is being actualised together with new_angle, so I can't calculate the difference.
I've tried many ways to solve this, but none of them were good enough. The best I did, was adding a counter variable, and actualising old_angle when counter was even and new_angle when counter was odd.
Here's my code:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345.h>
#include <math.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_ADXL345 accel = Adafruit_ADXL345(12345);
int outPin = 5;
int outPin2 = 6;
int outPin4 = 10;
int outPin3 = 11;
void setup(void)
{
Serial.begin(9600);
Serial.println("Accelerometer Test"); Serial.println("");
/* Initialise the sensor */
if(!accel.begin())
{
/* There was a problem detecting the ADXL345 ... check your connections */
Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
while(1);
}
/* Set the range to whatever is appropriate for your project */
accel.setRange(ADXL345_RANGE_2_G);
accel.setDataRate(ADXL345_DATARATE_1600_HZ);
pinMode(outPin, OUTPUT);
pinMode(outPin2, OUTPUT);
pinMode(outPin3, OUTPUT);
pinMode(outPin4, OUTPUT);
}
void loop(void)
{
sensors_event_t event;
accel.getEvent(&event);
float y = event.acceleration.y;
float z = event.acceleration.z;
float alfa_old;
// correction for each axis used
if(y>0)
y=event.acceleration.y-0.86;
if(y<0)
y=event.acceleration.y-0;
if(z>0)
z=event.acceleration.z+0.16;
if(z<0)
z=event.acceleration.z+1.02;
// calculating angles and acceleration
float alfa_new = atan2(y , z) * 180/PI;
float Dalfa=abs(alfa_new-alfa_old);
alfa_old = alfa_new;
/* Display the results (acceleration is measured in m/s^2) */
Serial.print("alfa_old: "); Serial.print(alfa_old); Serial.print(" ");
Serial.print("Dalfa: "); Serial.print(Dalfa); Serial.print(" ");
Serial.print("alfa_new: "); Serial.print(alfa_new); Serial.print(" ");
Serial.print("Y: "); Serial.print(y); Serial.print(" ");
Serial.print("Z: "); Serial.print(z); Serial.print(" ");Serial.println("m/s^2 ");
// demo work for engines
// if(y>=0){
// analogWrite(outPin, y+50);
// digitalWrite(outPin2, LOW); //prawy
// analogWrite(outPin3, 0);
// digitalWrite(outPin4, LOW);
// }
// if(y<=0){
// analogWrite(outPin, 0 );
// digitalWrite(outPin2, LOW); //lewy
//analogWrite(outPin3, abs(y)+50);
// digitalWrite(outPin4, LOW);
//}
delay(15);
}
Greetings and thanks for any help.