/*
################################################################################
# By CGi #
# #
# Feel free to copy, modify and do whatever you want with this project #
# Be aware that the use of many variables may consume more memory than wanted #
# #
# Created : Oct. 29th 2023 #
################################################################################
*/
int stepsPerClick = 5;
#define ENCODER_CLK 2
#define ENCODER_DT 3
#define ENCODER_SW 4
#include <Servo.h>
Servo ESC;
void setup() {
ESC.attach(9,1500,4000);
// Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_SW, INPUT_PULLUP);
}
int lastClk = HIGH;
long int swLastState = 0;
int counter = 0;
int escSpeed = 0;
void loop() {
int newClk = digitalRead(ENCODER_CLK);
int swPressed = digitalRead(ENCODER_SW);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
int dtValue = digitalRead(ENCODER_DT);
if (newClk == LOW && dtValue == HIGH) {
if (counter < 100) {
counter = counter + stepsPerClick;}
// Serial.println("Rotated clockwise ⏩");
// Serial.println(counter);
}
if (newClk == LOW && dtValue == LOW) {
if (counter > 0) {
counter = counter - stepsPerClick;}
// Serial.println("Rotated counterclockwise ⏪");
// Serial.println(counter);
}
}
if (swPressed == LOW && swLastState == 0 ) {
counter = 0;
// Serial.println("Button pressed");
// Serial.println(counter);
swLastState = millis();
}
if (swPressed == HIGH){
swLastState = 0;
}
escSpeed = map(counter,0,100,0,180);
ESC.write(escSpeed);
}