I'm building a little project to move the stepper motor according to the time the person keeps the switch pressed, and the longer the time, higher the speed. The code I'm using increases the speed and I can see it at Serial Monitor, but the stepper motor don't change. I would like to know if is it possible to change the speed of the stepper without the use of a potentiometer and how?
#include <Stepper.h>
const int ForwardLimitSwitchPin = 2;
const int ReverseLimitSwitchPin = 3;
const int StepperStepPin = 4;
const int StepperDirectionPin = 5;
const int LimitSwitchActivated = LOW; // Limit switch grounds pin
const int StepperMaxRPM = 255;//default = 100
const int swDireita = 13;
const int swEsquerda = 12;
int velMotor = 0;
static const unsigned long REFRESH_INTERVAL = 1000; // ms
static unsigned long lastRefreshTime = 0;
boolean flag;
//Stepper stepper(200, StepperStepPin, StepperDirectionPin);
Stepper stepper(200, 8, 9, 10, 11);
void setup() {
pinMode(swDireita, INPUT);
pinMode(swEsquerda, INPUT);
digitalWrite(swDireita, HIGH);
digitalWrite(swEsquerda, HIGH);
pinMode(ForwardLimitSwitchPin, INPUT_PULLUP);
pinMode(ReverseLimitSwitchPin, INPUT_PULLUP);
stepper.setSpeed(StepperMaxRPM);
Serial.begin(115200);
}
void loop() {
while (digitalRead(swDireita) == 0) {
motorDireita();
}
velMotor = 0;
while (digitalRead(swEsquerda) == 0) {
motorEsquerda();
}
velMotor = 0;
while (digitalRead(swDireita) == 0 && digitalRead(swEsquerda) == 0) {
motorParado();
}
velMotor = 0;
}
void motorParado() {
Serial.print("Ambos ativados, parada");
Serial.print("\n");
stepper.setSpeed(0);
stepper.step(0);
}
void motorDireita() {
//51 por segundo para 5 seg total
/*if(!flag){
flag = true;
velMotor = 51;
}else */
if (velMotor < 255 && millis() - lastRefreshTime >= REFRESH_INTERVAL) {
lastRefreshTime += REFRESH_INTERVAL;
velMotor += 25;
}
//int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
//int motorSpeed = map(velMotor, 0, 1023, 0, 255);
Serial.print("direita ativada, velocidade: ");
Serial.print(velMotor);
//Serial.print(motorSpeed);
Serial.print("\n");
stepper.setSpeed(velMotor);
//stepper.setSpeed(motorSpeed);
stepper.step(1);
}
void motorEsquerda() {
//51 por segundo para 5 seg total
if (velMotor < 255 && millis() - lastRefreshTime >= REFRESH_INTERVAL) {
lastRefreshTime += REFRESH_INTERVAL;
velMotor += 51;
}
Serial.print("Esquerda ativida, velocidade: ");
Serial.print(velMotor);
Serial.print("\n");
stepper.setSpeed(velMotor);
stepper.step(-1);
}