#include <TMCStepper.h>
#include <EEPROM.h>

#define PIN_ENABLE          2 // Enable
#define PIN_DIR             4 // Direction
#define PIN_STEP            3 // Step
#define PIN_POTENTIOMETER   A0

#define SW_RX               63 // TMC2208/TMC2224 SoftwareSerial receive pin
#define SW_TX               40 // TMC2208/TMC2224 SoftwareSerial transmit pinf
#define DRIVER_ADDRESS      0b00 // TMC2209 Driver address according to MS1 and MS2
#define R_SENSE             0.11f // Match to your driver, SilentStepStick series use 0.11

// Rotary Encoder Inputs

TMC2209Stepper driver(SW_RX, SW_TX, R_SENSE, DRIVER_ADDRESS);
float scaling = 1.0;
unsigned long last_run_time;
long interval_secs = 1200;

void setup()
{
  Serial.begin(115200);  
  pinMode(PIN_ENABLE, OUTPUT);
  pinMode(PIN_STEP, OUTPUT);
  pinMode(PIN_DIR, OUTPUT);
  pinMode(PIN_POTENTIOMETER, INPUT);
  digitalWrite(PIN_ENABLE, LOW);  // Enable driver in hardware
  //digitalRead(PIN_POTENTIOMETER);
  scaling = analogRead(PIN_POTENTIOMETER)/1023.0;

  driver.begin();                 //  SPI: Init CS pins and possible SW SPI pins
                                  // UART: Init SW UART (if selected) with default 115200 baudrate
  driver.toff(5);                 // Enables driver in software
  driver.rms_current(1200);        // Set motor RMS current
  driver.microsteps(16);          // Set microsteps to 1/16th
  
  driver.pwm_autoscale(true);     // Needed for stealthChop
  last_run_time = millis()-(interval_secs+1)*1000;
}


void loop() 
{  
  scaling = analogRead(PIN_POTENTIOMETER)/1023.0;
  int del = 600*scaling;
  if(del<100)
  {
    del = 100;
  }
  turn(5, del);
  
  unsigned long this_time; this_time = millis();
  if(abs(this_time-last_run_time)>interval_secs*1000)
  {
    del = 200;turn(5, del);
    del = 150;turn(5, del);
    del = 100;turn(20, del);
    last_run_time = this_time;
  }
}

void turn(float n_turns, int delay_microseconds)
{
  digitalWrite(PIN_ENABLE, LOW);
  for (long i = (long)(1600.0*n_turns); i>0; i--)
  {
    digitalWrite(PIN_STEP, HIGH);
    delayMicroseconds(delay_microseconds);
    digitalWrite(PIN_STEP, LOW);
    delayMicroseconds(delay_microseconds);
  }
  digitalWrite(PIN_ENABLE, HIGH);
}
