#include <AccelStepper.h>
#define motorPin1 8 // IN1 on the ULN2003 driver
#define motorPin2 9 // IN2 on the ULN2003 driver
#define motorPin3 10 // IN3 on the ULN2003 driver
#define motorPin4 11 // IN4 on the ULN2003 driver
#define switchPin 2
#define MIN_ELAPSED_TIME 1000
const int rpmSlow = 10;
const int rpmFast = 15;
unsigned long duration;
AccelStepper stepper(4, motorPin1, motorPin3, motorPin2, motorPin4);
void setup() {
// put your setup code here, to run once:
pinMode(switchPin, INPUT_PULLUP);
stepper.setMaxSpeed(rpmSlow * 2048 / 60); // Set initial speed to 10 rpm
//stepper.setMaxSpeed(820); // 24rpm
stepper.setAcceleration(1000);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int switchState = digitalRead(switchPin);
if (switchState == LOW) {
Serial.println(switchState);
duration = millis(); // Record the start time
stepper.setSpeed(rpmFast * 2048 / 60); // Set speed to 15 rpm
// duration = millis();
}else {
if (duration - millis()> MIN_ELAPSED_TIME) {
Serial.println(switchState);
stepper.setSpeed(rpmSlow * 2048/60); // convert rpm to steps per minute (15 rpm)
}
}
//move the motor
stepper.runSpeed();
}
the problem in my program is that the when I pressed the pushbutton it doesnt't change to 15 rpm . The stepper motor will have 15 rpm if the button is pressed , and if the pushbutton is released it will go back to its 10 rpm default.
It won't change to 15RPM as long as you set the maximum speed limit to 10RPM in setup.
Also, because 'millis()' is most likely larger than 'duration' and the math is done with unsigned longs, this will likely not hold the switch for MIN_ELAPSED_TIME:
And whoever wrote this code likely intended to do the difference the opposite way.
//Create a program that will make the stepper motor produce 15RPM is the switch is pressed, and 10 RPM if the switch is unpressed./
#include <AccelStepper.h>
// Define the pins connected to the stepper motor driver #define motorPin1 8 #define motorPin2 10 #define motorPin3 9 #define motorPin4 11
// Define the pin connected to the switch #define switchPin 2 #define MIN_ELAPSED_TIME 1000
// Define RPM values
const int rpmSlow = 10;
const int rpmFast = 15;
unsigned long preTime;
int preSwitchState = HIGH;
bool fastRPMState = true;
// Create an instance of the AccelStepper class
AccelStepper stepper(4, motorPin1, motorPin2, motorPin3, motorPin4);
void setup() {
// Set the switch pin as input
pinMode(switchPin, INPUT_PULLUP);
// Set the maximum speed and acceleration for the stepper motor
stepper.setMaxSpeed(2048 / 60);
// stepper.setMaxSpeed (820);
stepper.setAcceleration(1000);
}
void loop() {
// Read the state of the switch
int switchState = digitalRead(switchPin);
// If the switch changed, due to noise or pressing:
if (switchState != preSwitchState) {
// reset the debouncing timer
preTime = millis();
}