Hello everyone!
I'm currently working on balancing an inverted pendulum with a Fuzzy controller and I use a stepper motor to drive the balancing cart. My problem arises from this part because I cannot think up a proper way to control the motor.
The fuzzy controller sends the calculated response to the Arduino Nano through USB and the program reads it fine (using the Serial.parseInt() function). So far I've been using the AccelStepper library and I got the acceleration part down, but positioning of the cart is still unsolved. I need the motor to rapidly change the direction and/or the acceleration if a new response value comes in from the FLC.
#include <AccelStepper.h>
//Driver setup
AccelStepper motor(1, 5, 4); //DRIVER mode, STEP: 5, DIR: 4)
int FuzzyAccel = 1000;
int Enable = 6; //for the stepper motor EN pin
void setup() {
//Start of serial comms
Serial.begin(115200);
//activating Driver EN pin
pinMode(Enable, OUTPUT);
digitalWrite(Enable, LOW);
//Init values
motor.setMaxSpeed(6000);
motor.setMinPulseWidth(1);
motor.setCurrentPosition(0);
motor.setAcceleration(15000);
//Wait for start signal from the controller
while (Serial.available() && Serial.read()); // empty buffer
while (!Serial.available()); // wait for data
while (Serial.available() && Serial.read()); // empty buffer again
}
void loop() {
while (Serial.available()) {
//Reads the response value from the controller
FuzzyAccel = Serial.parseInt();
//Negative direction run
if (FuzzyAccel < 0) {
motor.setAcceleration(abs(FuzzyAccel));
motor.moveTo(-1000);
negRun();
}
else if (FuzzyAccel > 0) {
motor.setAcceleration(FuzzyAccel);
motor.moveTo(1000);
posRun();
}
}
}
////////////////////////////////////////////
//Subrutine for negative running
void negRun() {
while (FuzzyAccel < 0) {
motor.run();
if(FuzzyAccel < 0) break;
}
}
//Subrutine for positive running
void posRun() {
while (FuzzyAccel > 0) {
motor.run();
if (FuzzyAccel < 0) break;
}
}
Currently what the program does is runs the motor toward a direction but only once. After the cart stopped nothing happens.
I'm pretty new to Arduino and I don't fully understand the programming logic behind it.
I'm using an Arduino Nano with a A4988 stepper motor driver. If you have any tips or ideas for what to change, I'd appreciate it.