Hi All,
I wanted to know if it's possible to set a variable to a range or any value between two values.
Here's a brief reason as to why I'm attempting this in case there is a better way for me to go about things.
I'm trying to programme a PID controlled thrust vector system to self balance. I want to set the "Setpoint" (the desired output value) to an accelerometer range between -0.5 and 0.5 to allow for some wiggle room and so that there is no overcorrection or over reaction to slide wobbles or vibration.
Here is what I've got so far.
#include <ESP32Servo.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <PID_v1.h>
Adafruit_MPU6050 mpu;
int s1 = 2;
Servo x1;
double Setpoint, Input, Output;
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);
void setup(void) {
Serial.begin(115200);
while (!Serial) {
delay(10); // will pause Zero, Leonardo, etc until serial console opens
}
ESP32PWM::allocateTimer(0);
ESP32PWM::allocateTimer(1);
ESP32PWM::allocateTimer(2);
ESP32PWM::allocateTimer(3);
x1.setPeriodHertz(50);
x1.attach(s1, 500, 2400);
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
mpu.setAccelerometerRange(MPU6050_RANGE_16_G);
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.println("");
delay(100);
x1.write(0);
Setpoint = 0;
myPID.SetMode(AUTOMATIC);
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
Input = a.acceleration.x;
delay(100);
double gap = abs(Setpoint-Input);
if (gap < 2); {
myPID.SetTunings(consKp, consKi, consKd);
}
if (gap > 2); {
myPID.SetTunings(aggKp, aggKi , aggKd);
}
myPID.Compute();
int x = map(Output, 0, 255, 0, 180);
x1.write(x);
Serial.print(x);
Serial.print(" / ");
Serial.print(Input);
Serial.print(" / ");
Serial.println(gap);
}
I have yet to test the system (still waiting for some components) so the values plugged into the PID are completely arbitrary and I'm sure there are plenty of things wrong with it that I'll figure out along the way.
Just to highlight, the variable I wish to adjust is.
Setpoint = 0
Please let me know if there is a way to set the setpoint to a range or if there is a better way to go around attempting this.
Thanks in advanced!