#include <esp_event.h>

bool STATE = HIGH;
uint8_t PIN = 17;
uint8_t BTN_DOWN_PIN = 21;
uint8_t BTN_UP_PIN = 22;

int lastBtnState = HIGH;
int btn1State;
int btn2State;

hw_timer_t * timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

int speed = 100;
int pw;
int steps = 0;
int rpm = 0;
int startTime = 0;
int timeTo200Steps = 0;

int highStatePw = 1000;
int lowStatePw = 1000;

void calcRPM() {
  if (timeTo200Steps - startTime) {
    int elapsed = timeTo200Steps - startTime;
    int minMilliSecs = 60*1000;
    rpm = floor(minMilliSecs/elapsed);
  }
}

int nextPw() {
  return (speed*50/100)*1000;
}

void IRAM_ATTR onTimer() {
  portENTER_CRITICAL_ISR(&timerMux);
  STATE = STATE ? LOW : HIGH;
  pw = STATE ? highStatePw : lowStatePw;
  digitalWrite(PIN, STATE);
  timerAlarmWrite(timer, pw, true);
  portEXIT_CRITICAL_ISR(&timerMux);
}

void setupTimer() {
  timer = timerBegin(0, 80, true);
  timerAttachInterrupt(timer, &onTimer, true);
  pw = highStatePw;
  //pw = nextPw();
  timerAlarmWrite(timer, pw, true);
  timerAlarmEnable(timer);
  startTime = millis();
}

void setup() {
  pinMode(PIN, OUTPUT);
  pinMode(BTN_DOWN_PIN, INPUT_PULLUP);
  pinMode(BTN_UP_PIN, INPUT_PULLUP);
  // put your setup code here, to run once:
  setupTimer();
  Serial.begin(115200);
  Serial.println("Hello, ESP32-S2!");
}

void loop() {
  btn1State = digitalRead(BTN_DOWN_PIN);
  btn2State = digitalRead(BTN_UP_PIN);
  Serial.println("**************************************************************************************");
  if (btn1State == LOW) {
    speed = speed+1;
  }
  if (btn2State == LOW && speed > 0) {
    speed = speed-1;
  }
  // lastBtnState = curBtnState;
  Serial.printf("Speed: %i", speed);
  Serial.println();
  Serial.printf("PW: %i", pw);
  Serial.println();
  Serial.printf("RPM: %i", rpm);
  Serial.println();
  Serial.printf("STEPS: %i", steps);
  Serial.println();
  Serial.printf("StartMS: %i TTS: %i", startTime, timeTo200Steps);
  Serial.println();
  Serial.println();
  // put your main code here, to run repeatedly:
  delay(10); // this speeds up the simulation
}
A4988