/*
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-rotary-encoder-servo-motor
*/
#include <Servo.h>
#define CLK_PIN 2
#define DT_PIN 3
#define SW_PIN 4
#define SERVO_PIN 9
#define DIRECTION_CW 0 // clockwise direction
#define DIRECTION_CCW 1 // counter-clockwise direction
int counter = 0;
int direction = DIRECTION_CW;
int CLK_state;
int prev_CLK_state;
Servo servo; // create servo object to control a servo
void setup() {
Serial.begin(9600);
// configure encoder pins as inputs
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
// read the initial state of the rotary encoder's CLK pin
prev_CLK_state = digitalRead(CLK_PIN);
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
servo.write(0);
}
void loop() {
// read the current state of the rotary encoder's CLK pin
CLK_state = digitalRead(CLK_PIN);
// If the state of CLK is changed, then pulse occurred
// React to only the rising edge (from LOW to HIGH) to avoid double count
if (CLK_state != prev_CLK_state && CLK_state == HIGH) {
// if the DT state is HIGH
// the encoder is rotating in counter-clockwise direction => decrease the counter
if (digitalRead(DT_PIN) == HIGH) {
counter--;
direction = DIRECTION_CCW;
} else {
// the encoder is rotating in clockwise direction => increase the counter
counter++;
direction = DIRECTION_CW;
}
Serial.print("DIRECTION: ");
if (direction == DIRECTION_CW)
Serial.print("Clockwise");
else
Serial.print("Counter-clockwise");
Serial.print(" | COUNTER: ");
Serial.println(counter);
if (counter < 0)
counter = 0;
else if (counter > 180)
counter = 180;
// sets the servo angle according to the counter
servo.write(counter);
}
// save last CLK state
prev_CLK_state = CLK_state;
}
/*
Подключите поворотный энкодер и серводвигатель к цифровому пину Arduino.
Используйте библиотеку Servo.h для управления серводвигателем.
Реализуйте управление углом поворота серводвигателя с помощью энкодера:
При вращении по часовой стрелке угол увеличивается.
При вращении против часовой стрелки угол уменьшается.
Ограничьте угол поворота в диапазоне от 0° до 180°.
Добавьте кнопку для сброса угла в начальное положение (0°).
Отображайте текущий угол поворота в мониторе порта Arduino.
*/