Hi there,
I am working on an inverted pendulum project and it is a kind of moving cart driven by a (stepper) motor setup. I have an UNO, a NEMA 17, A4988 driver and IMU as a sensor. At the moment, I am really struggling with the control the stepper using AccelStepper.
// Include the AccelStepper Library
#include <AccelStepper.h>
// Define pin connections
const int dirPin = 2;
const int stepPin = 3;
// Define motor interface type
#define motorInterfaceType 1
// Creates an instance
AccelStepper stepper(motorInterfaceType, stepPin, dirPin);
int steps =200; //steps to move
void setup() {
// set the maximum speed, acceleration
stepper.setMaxSpeed(2500);
stepper.setAcceleration(50000);
stepper.setSpeed(1000);
}
void move_stepper(int value){
if (stepper.distanceToGo() == 0) {
stepper.moveTo(value);
} else {
stepper.run();
}
}
void loop() {
move_stepper(steps);
steps = -1*steps; // Change direction once the motor reaches target position
}
First of all, above is the code I run for testing. Basically, it is just running 200 steps forward and backward. It works well as I expected. By running this, I can see the cart can make the pendulum swing. So, I believe the torque/speed generated by the system is capable to perform the task (balancing the pole).
But when I tried to control the motor with sensor's reading...
#include <AccelStepper.h>
// Define pin connections
const int dirPin = 2;
const int stepPin = 3;
// Define motor interface type
#define motorInterfaceType 1
// Creates an instance
AccelStepper stepper(motorInterfaceType, stepPin, dirPin);
int steps =200; //steps to move
void setup() {
Serial.begin(9600);
//stepper setup
stepper.setMaxSpeed(2500);
stepper.setAcceleration(90000);
stepper.setSpeed(1000);
}
void move_stepper(int value){
if (stepper.distanceToGo() == 0) {
stepper.moveTo(value);
} else {
stepper.run();
}
}
void loop() {
u := readingFromSensors; //degree at the moment
if (u>10){
move_stepper(steps);
}
if (u<-10) {
move_stepper(-1*steps);
}
}
Let u be the reading from my sensor. What I intended to do is just moving the cart 200 steps forward if the pole inclines 10 degree to the right while 200 steps backward if it inclines to the left. (I totally understand this should not be good enough to balance the pole well.) But even with a simple case like that, the stepper is not moving as I intended to do. It is actually moving less than 200 steps and totally out of control.
May I know how should I modify my move stepper function? Also, for those had experience doing similar projects, any advice is welcome
Thank you!