Hi here, I am a newbee in programming. Trying to control stepper with rotary encoder. Checked many sources but did find exactly what I need, Can somebody have a look and advise. I like to increase/decrease the speed by 1 RPM every time I am turning the encoder left/right.
Thanks
#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
volatile boolean TurnDetected; // need volatile for Interrupts
volatile boolean rotationdirection; // CW or CCW rotation
const int PinCLK=2; // Generating interrupts using CLK signal
const int PinDT=3; // Reading DT signal
const int PinSW=4; // Reading Push Button switch
int rpm = 60; // counter for rpm, start value = 60
// Interrupt routine runs if CLK goes from HIGH to LOW
void isr () {
delay(4); // delay for Debouncing
if (digitalRead(PinCLK))
rotationdirection= digitalRead(PinDT);
else
rotationdirection= !digitalRead(PinDT);
TurnDetected = true;
}
void setup () {
pinMode(PinCLK,INPUT);
pinMode(PinDT,INPUT);
pinMode(PinSW,INPUT);
digitalWrite(PinSW, HIGH); // Pull-Up resistor for switch
attachInterrupt (0,isr,FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
// set the speed at default rpm:
myStepper.setSpeed(rpm);
}
void loop () {
myStepper.step(stepsPerRevolution); //starts stepper ar default speed
// Runs if rotation was detected
if (TurnDetected) {
TurnDetected = false; // do NOT repeat IF loop until new rotation detected
// increase/decrease the speed
if (rotationdirection) { // incerease speed
rpm++;
myStepper.setSpeed(rpm);
myStepper.step(stepsPerRevolution);
rpm = rpm++; // save current rpm value into previous variable
}
if (!rotationdirection) { { // decrease speed
rpm--;
myStepper.setSpeed(rpm);
myStepper.step(stepsPerRevolution);
rpm = rpm--; // save current rpm value into previous variable
}
}
}
}