/*
################################################################################
# By DrCrowller #
# #
# 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 : 7 Apr. 2022 #
################################################################################
*/
#include <Servo.h>
Servo arm; // Create a "Servo" object called "arm"
float pos = 0.0; // Variable where the arm's position will be stored (in degrees)
float step = 1.0; // Variable used for the arm's position step
#define ENCODER_CLK 2
#define ENCODER_DT 3
void setup()
{
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
arm.attach(4); // Attache the arm to the pin 2
arm.write(pos); // Initialize the arm's position to 0 (leftmost)
Serial.begin(9600);
}
int lastClk = HIGH;
void loop()
{
int newClk = digitalRead(ENCODER_CLK);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
int dtValue = digitalRead(ENCODER_DT);
if (newClk == LOW && dtValue == HIGH) {
if (pos>0) // Check that the position won't go lower than 0°
{
arm.write(pos); // Set the arm's position to "pos" value
pos-=5*step; // Decrement "pos" of "step" value
Serial.println(pos);
delay(5); // Wait 5ms for the arm to reach the position
}
Serial.println("Rotated clockwise ⏩");
}
if (newClk == LOW && dtValue == LOW) {
if (pos<180) // Check that the position won't go higher than 180°
{
arm.write(pos); // Set the arm's position to "pos" value
pos+=5*step; // Increment "pos" of "step" value
Serial.println(pos);
delay(5); // Wait 5ms for the arm to reach the position
}
Serial.println("Rotated counterclockwise ⏪");
}
}
}