Here is example 2: I want that whenever the rotary encoder rotates, the stepper motor should move clockwise only in one direction and stops when the rotary encoder is not rotating. (it drives a 300mm actuator linear slider)
/* Arduino Rotary Encoder Tutorial
*
- by Dejan Nedelkovski, www.HowToMechatronics.com
*/
#include <SPI.h>
#include <TMC26XStepper.h>
//we have a stepper motor with 200 steps per rotation, CS pin 2, dir pin 6, step pin 7 and a current of 800mA
TMC26XStepper tmc26XStepper = TMC26XStepper(200,6,4,5,800);
int curr_step;
int speed = 0;
int speedDirection = 100;
int maxSpeed = 1000;
#define outputA 2
#define outputB 3
int counter = 0;
int aState;
int aLastState;
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
Serial.println("==============================");
Serial.println("TMC26X Stepper Driver Demo App");
Serial.println("==============================");
//set this according to you stepper
Serial.println("Configuring stepper driver");
//char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement
tmc26XStepper.setSpreadCycleChopper(2,24,8,6,0);
tmc26XStepper.setRandomOffTime(0);
tmc26XStepper.setMicrosteps(128);
tmc26XStepper.setStallGuardThreshold(4,0);
Serial.println("config finished, starting");
Serial.println("started");
}
void loop() {
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
(!tmc26XStepper.isMoving());
speed+=speedDirection;
if (speed>maxSpeed) {
speed = maxSpeed;
speedDirection = -speedDirection;
} else if (speed<0) {
speedDirection = -speedDirection;
speed=speedDirection;
}
//setting the speed
Serial.print("setting speed to ");
Serial.println(speed);
tmc26XStepper.setSpeed(speed);
//we want some kind of constant running time - so the length is just a product of speed
Serial.print("Going ");
Serial.print(10speed);
Serial.println(" steps");
tmc26XStepper.step(10speed);
}
} else {
counter --;
//we put out the status every 100 steps
if (tmc26XStepper.getStepsLeft()%200==0) {
Serial.print("Stall Guard: ");
Serial.println(tmc26XStepper.getCurrentStallGuardReading());
}
Serial.print("Position: ");
Serial.println(counter);
aLastState = aState; // Updates the previous state of the outputA with the current state
tmc26XStepper.move();}
}