To get the reading of position encoder sensor direction change using Raspberry Pi Pico
Required Components
Position encoder sensor_1 no
Raspberry Pi Pico_1 no
Connecting Wires_4 set
Circuit
Steps
Make sure the components are working properly.
Connect the position encoder sensor to the Raspberry Pi Pico.
Connect the Raspberry Pi Pico pin GP8 & GP9 to Position encoder sensor CLK & DT pin and Position encoder SW pin to the GP2 of Raspberry Pi Pico.
Connect the +5v and ground(gnd) connections respectively.
Check the Python program.
Check the Electrical Circuit.
Run the Python program.
Python Program
from machine import Pin
import utime
DT_Pin = Pin(9, Pin.IN, Pin.PULL_UP)
CLK_Pin = Pin(8, Pin.IN, Pin.PULL_UP)
SW = Pin(2, Pin.IN, Pin.PULL_UP)
LEDs = [25,4]
#create an empty list to assing pins in pico
led_pins = []
for x in range(0,2):
led_pins.append(Pin(LEDs[x], Pin.OUT))
value = 0
previousValue = 1
def rotary_changed():
global previousValue
global value
if previousValue != CLK_Pin.value():
if CLK_Pin.value() == 0:
if DT_Pin.value() == 0:
value = (value - 1)%2
print("anti-clockwise", value)
else:
value = (value + 1)%2
print("clockwise", value)
previousValue = CLK_Pin.value()
if SW.value() == 0:
print("Button pressed")
utime.sleep(1)
while True:
for i in range(0,2):
led_pins[i].value(0)
rotary_changed()
led_pins[value].value(1)
utime.sleep(0.001)
Connect Raspberry Pi Pico board VBus and GND pin to the bread board by using wires.
Connect 220 Ω Resistor to the LED Anode (+) pin and LED cathode (-) pin to Gnd.
Connect 220 Ω Resistor another pin to GP16.
Connect 10 k Ω Resistor to the switch button.
Connect switch button another pin to the Raspberry Pi Pico pin GP17.
When we press the push button LED blinks.
Check the Python program.
Check the circuit connections.
Run the Python program.
Python Program
from machine import Pin
from time import sleep
led_pin = Pin(16, Pin.OUT) # 16 number in is Output
push_button = Pin(17, Pin.IN) # 17 number pin is input
while True:
logic_state = push_button.value()
if logic_state == True: # if push_button pressed
led_pin.value(1) # led will turn ON
else: # if push_button not pressed
led_pin.value(0)