Hi gurus,
I'm using accelstepper library to control the motor. The requirement is to make the motor to rotate 180 degree back and forth (1 cycle), complete 30 cycles in one minute.
I have written the program as below, however it takes around 1minute 24 secs to complete 30 cycles. Thank you in advance for your input.
#include <AccelStepper.h>
#define stepPin 9
#define dirPin 8
#define En 4
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);
int stepsPerRevolution = 1600; // steps per revolution
int stepsPerHalfRevolution = stepsPerRevolution / 2; // steps for 180 degrees
const int totalCycles = 30; // total cycles
const int totalTimeSeconds = 60; // total time in seconds
const int timePerCycle = totalTimeSeconds / totalCycles; // time per cycle in seconds
const int timePerHalfMove = timePerCycle / 2; // time for 180-degree move (1 second)
float stepsPerSecond = float(stepsPerHalfRevolution) / timePerHalfMove; // steps per second
float stepsPerSecond_S = stepsPerSecond * 2;
void setup() {
pinMode(En, OUTPUT);
Serial.begin(9600);
stepper.setMaxSpeed(stepsPerSecond); // Set speed to achieve 180 degrees in 1 second
stepper.setAcceleration(stepsPerSecond_S); // Set acceleration
}
void loop() {
if (Serial.available()) {
String data_from_display = "";
delay(10);
while (Serial.available()) {
data_from_display += char(Serial.read());
}
sendData(data_from_display);
}
}
void Start() {
Serial.println("START invert");
for (int x = 0; x < totalCycles; x++) {
// Move 180 degrees clockwise
stepper.moveTo(stepper.currentPosition() + stepsPerHalfRevolution);
while (stepper.distanceToGo() != 0) {
stepper.run();
}
// Move 180 degrees counterclockwise
stepper.moveTo(stepper.currentPosition() - stepsPerHalfRevolution);
while (stepper.distanceToGo() != 0) {
stepper.run();
}
if (Serial.available()) {
String data_from_display = "";
//delay(30);
while (Serial.available()) {
data_from_display += char(Serial.read());
}
if (data_from_display == "S")
stepper.stop();
break;
}
}
delay(2000);
digitalWrite(En, LOW); //disable motor drive to make it free rotate
Serial.println("DISABLE");
}
void sendData(String data_from_display) {
if (data_from_display == "START") {
Start();
}
if (data_from_display == "disEn") {
digitalWrite(En, LOW);
Serial.println("DISABLE");
}
if (data_from_display == "En") {
digitalWrite(En, HIGH);
Serial.println("EN");
}
if (data_from_display == "200") {
stepsPerRevolution =200;
Serial.println("200");
}
if (data_from_display == "400") {
stepsPerRevolution =400;
Serial.println("400");
}
if (data_from_display == "800") {
stepsPerRevolution =800;
Serial.println("800");
}
}