'''
Pinout:
A4988-1:
Step = 17
Dir = 16
A4988-2:
Step = 5
Dir = 16
Rotary Encoder:
DT = 18
CLK = 19
SW = 21
'''
from machine import Pin
import time
class Port:
def __init__(self, pin_nums):
self.pins = [Pin(num, Pin.OUT) for num in pin_nums]
def write(self, value):
for i, p in enumerate(self.pins):
p.value((value >> i) & 1)
def LCD_cmd(RS,E,LCD_Port,cmd):
RS.value(0)
MSN = (cmd & 0xF0) >> 4
LSN = cmd & 0x0F
LCD_Port.write(MSN)
E.value(1)
time.sleep(0.005)
E.value(0)
time.sleep(0.005)
LCD_Port.write(LSN)
E.value(1)
time.sleep(0.005)
E.value(0)
time.sleep(0.005)
def LCD_data(RS,E,LCD_Port,data):
RS.value(1)
MSN = (data & 0xF0) >> 4
LSN = data & 0x0F
LCD_Port.write(MSN)
E.value(1)
time.sleep(0.005)
E.value(0)
time.sleep(0.005)
LCD_Port.write(LSN)
E.value(1)
time.sleep(0.005)
E.value(0)
time.sleep(0.005)
def LCD_init(RS,E,LCD_Port):
LCD_cmd(RS,E,LCD_Port,0x32)
LCD_cmd(RS,E,LCD_Port,0x0C)
LCD_cmd(RS,E,LCD_Port,0x01)
time.sleep(0.002) # זמן מחיקה ארוך יותר
LCD_cmd(RS,E,LCD_Port,0x06)
def LCD_Print(RS,E,LCD_Port,string):
for val in string:
LCD_data(RS,E,LCD_Port,ord(val))
def LCD_setCursor(RS,E,LCD_Port,x,y):
if(y==1):
LCD_cmd(RS,E,LCD_Port,0x80 | x)
elif(y==2):
LCD_cmd(RS,E,LCD_Port,0xC0 | x)
step1 = Pin(17,Pin.OUT,value=0)
step2 = Pin(5,Pin.OUT,value=0)
direction = Pin(16,Pin.OUT,value=0)
LCD_Port = Port([16, 4, 0, 2]) # D4, D5, D6, D7
RS = Pin(23,Pin.OUT, value=0)
E = Pin(22,Pin.OUT, value=0)
DT = Pin(18,Pin.IN)
CLK = Pin(19,Pin.IN)
SW = Pin(21,Pin.IN)
count = 0
LCD_init(RS,E,LCD_Port)
LCD_setCursor(RS,E,LCD_Port,0,1)
LCD_Print(RS,E,LCD_Port,f'Count: {count}')
last_clk_val = 1
motor = 0
x = 0
y = 0
LCD_setCursor(RS,E,LCD_Port,0,2)
LCD_Print(RS,E,LCD_Port,f'X={x},Y={y} ')
while True:
if(SW.value() == 0):
motor = not motor
while(SW.value() == 0):
time.sleep_ms(1)
new_clk_val = CLK.value()
if(not(new_clk_val == last_clk_val)):
last_clk_val = new_clk_val
dt_val = DT.value()
if(new_clk_val == 0 and dt_val == 1):
print('CW')
direction.value(1)
if(motor == 0):
step1.value(1)
time.sleep_ms(5)
step1.value(0)
x=x+1
else:
step2.value(1)
time.sleep_ms(5)
step2.value(0)
y=y+1
count = count + 1
if(new_clk_val == 0 and dt_val == 0):
print('CCW')
direction.value(0)
if(motor == 0):
step1.value(1)
time.sleep_ms(5)
step1.value(0)
x=x-1
else:
step2.value(1)
time.sleep_ms(5)
step2.value(0)
y=y-1
count = count - 1
LCD_setCursor(RS,E,LCD_Port,0,1)
LCD_Print(RS,E,LCD_Port,f'Count: {count} ')
LCD_setCursor(RS,E,LCD_Port,0,2)
LCD_Print(RS,E,LCD_Port,f'X={x},Y={y} ')