Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
2.1.6 Rotary Encoder Module¶
Introduction¶
In this project, you will learn about Rotary Encoder. A rotary encoder is an electronic switch with a set of regular pulses in strictly timing sequence. When used with IC, it can achieve increment, decrement, page turning and other operations such as mouse scrolling, menu selection, and so on.
Required Components¶
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
---|---|---|
Raphael Kit |
337 |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
---|---|
Schematic Diagram¶
Experimental Procedures¶
Step 1: Build the circuit.
In this example, we can connect the Rotary Encoder pin directly to the Raspberry Pi using a breadboard and 40-pin Cable, connect the GND of the Rotary Encoder to GND, 「+」to 5V, SW to digital GPIO27, DT to digital GPIO18, and CLK to digital GPIO 17.
Step 2: Open the code file.
cd ~/raphael-kit/python-pi5
Step 3: Run.
sudo python3 2.1.6_RotaryEncoder_zero.py
You will see the count on the shell. When you turn the rotary encoder clockwise, the count is increased; when turn it counterclockwise, the count is decreased. If you press the switch on the rotary encoder, the readings will return to zero.
Code
Note
You can Modify/Reset/Copy/Run/Stop the code below. But before that, you need to go to source code path like raphael-kit/python-pi5
. After modifying the code, you can run it directly to see the effect.
#!/usr/bin/env python3
from gpiozero import RotaryEncoder, Button
from time import sleep
# Initialize the rotary encoder and button
encoder = RotaryEncoder(a=17, b=18) # Rotary Encoder connected to GPIO pins 17 (CLK) and 18 (DT)
button = Button(27) # Button connected to GPIO pin 27
global_counter = 0 # Track the rotary encoder's position
def rotary_change():
""" Update the global counter based on the rotary encoder's rotation. """
global global_counter
global_counter += encoder.steps # Adjust counter based on encoder steps
encoder.steps = 0 # Reset encoder steps after updating counter
print('Global Counter =', global_counter) # Display current counter value
def reset_counter():
""" Reset the global counter to zero when the button is pressed. """
global global_counter
global_counter = 0 # Reset the counter
print('Counter reset') # Indicate counter reset
# Assign the reset_counter function to button press event
button.when_pressed = reset_counter
try:
# Monitor rotary encoder continuously and process changes
while True:
rotary_change() # Handle rotary encoder changes
sleep(0.1) # Short delay to reduce CPU load
except KeyboardInterrupt:
# Gracefully handle a keyboard interrupt (Ctrl+C)
pass
Code Analysis
Imports the
RotaryEncoder
andButton
classes from thegpiozero
library, and thesleep
function for delays.#!/usr/bin/env python3 from gpiozero import RotaryEncoder, Button from time import sleep
Initializes the rotary encoder with GPIO pins 17 and 18, and a button on GPIO pin 27.
# Initialize the rotary encoder and button encoder = RotaryEncoder(a=17, b=18) # Rotary Encoder connected to GPIO pins 17 (CLK) and 18 (DT) button = Button(27) # Button connected to GPIO pin 27
Declares a global variable
global_counter
to track the position of the rotary encoder.global_counter = 0 # Track the rotary encoder's position
Defines a function
rotary_change
to update the global counter based on the rotary encoder’s rotation.def rotary_change(): """ Update the global counter based on the rotary encoder's rotation. """ global global_counter global_counter += encoder.steps # Adjust counter based on encoder steps encoder.steps = 0 # Reset encoder steps after updating counter print('Global Counter =', global_counter) # Display current counter value
Defines a function
reset_counter
to reset the global counter to zero when the button is pressed.def reset_counter(): """ Reset the global counter to zero when the button is pressed. """ global global_counter global_counter = 0 # Reset the counter print('Counter reset') # Indicate counter reset
Assigns the
reset_counter
function to be called when the button is pressed.# Assign the reset_counter function to button press event button.when_pressed = reset_counter
In a continuous loop, the script calls
rotary_change
to handle rotary encoder changes and introduces a short delay to reduce CPU load. Uses a try-except block to handle KeyboardInterrupts gracefully.try: # Monitor rotary encoder continuously and process changes while True: rotary_change() # Handle rotary encoder changes sleep(0.1) # Short delay to reduce CPU load except KeyboardInterrupt: # Gracefully handle a keyboard interrupt (Ctrl+C) pass