Arduino - Encoder Rotativo - Servo Motor
Neste tutorial, vamos aprender a programar o Arduino para girar um servo motor de acordo com o valor de saída do encoder rotativo.
Hardware Necessário
Or you can buy the following kits:
| 1 | × | DIYables STEM V3 Starter Kit (Arduino included) | |
| 1 | × | DIYables Sensor Kit (18 sensors/displays) |
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.
Buy Note: For controlling multiple servo motors, use the PCA9685 16 Channel PWM Servo Driver Module to save MCU pins and simplify wiring.
Sobre o Servo Motor e o Encoder Rotativo
Se você ainda não conhece o servo motor e o encoder rotativo (pinagem, como funcionam, como programar ...), aprenda sobre eles nos seguintes tutoriais:
Diagrama de Ligação

This image is created using Fritzing. Click to enlarge image
Código Arduino
/*
* Este código de Arduino foi desenvolvido por pt.newbiely.com
* Este código de Arduino é disponibilizado ao público sem nenhuma restrição.
* Para tutoriais completos e diagramas de ligação, visite:
* https://pt.newbiely.com/tutorials/arduino/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;
}
Passos Rápidos
- Conecte o Arduino ao PC via cabo USB
- Abra o Arduino IDE, selecione a placa e a porta corretas
- Copie o código acima e abra-o no Arduino IDE
- Clique no botão Upload no Arduino IDE para carregar o código no Arduino

- Abra o Serial Monitor
- Gire o encoder rotativo
- Observe a rotação do servo motor
- Veja o resultado no Serial Monitor
8
Serial.println("Hello World!");
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
DIRECTION: Clockwise | COUNTER/ANGLE: 19
DIRECTION: Clockwise | COUNTER/ANGLE: 26
DIRECTION: Clockwise | COUNTER/ANGLE: 34
DIRECTION: Clockwise | COUNTER/ANGLE: 46
DIRECTION: Clockwise | COUNTER/ANGLE: 53
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 46
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 34
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 26
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 16
DIRECTION: Counter-clockwise | COUNTER/ANGLE: 06
Explicação do Código
Leia a explicação linha por linha nas linhas de comentário do código-fonte!