from machine import Pin, PWM
from time import sleep
from math import floor
import utime
a=0
# Connect Keypad pins as below
col_list=[1,2,3,4]
row_list=[5,6,7,8]
tombol = Pin(16, Pin.IN)
pwm = PWM(Pin(15))
pwm.freq(50)
duty = 0
pwm.duty_u16(duty)
sleep(0.1)
min_duty = 1700
max_duty = 10250
min_degrees = 0
max_degrees = 180
def degrees_to_duty(degrees):
duty_step = ((max_duty - min_duty) / max_degrees)
if degrees > max_degrees:
degrees = max_degrees
elif degrees < min_degrees:
degrees = min_degrees
duty = floor((duty_step * degrees)+ min_duty)
if duty > max_duty:
duty = max_duty
elif duty < min_duty:
duty = min_duty
return duty
duty = degrees_to_duty(0)
pwm.duty_u16(duty)
sleep(1)
#Set rows pin as output
for x in range(0,4):
row_list[x]=Pin(row_list[x], Pin.OUT)
row_list[x].value(1)
#Set column as input
for x in range(0,4):
col_list[x] = Pin(col_list[x], Pin.IN, Pin.PULL_UP)
# Create a map between keypad buttons and chars
key_map=[["D","#","0","*"],\
["C","9","8","7"],\
["B","6","5","4"],\
["A","3","2","1"]]
def Keypad4x4Read(cols,rows):
for r in rows:
r.value(0)
result=[cols[0].value(),cols[1].value(),cols[2].value(),cols[3].value()]
if min(result)==0:
key=key_map[int(rows.index(r))][int(result.index(0))]
r.value(1) # manages key keept pressed
return(key)
r.value(1)
# Start the main loop
print("--- Ready to get user inputs ---")
while True:
key=Keypad4x4Read(col_list, row_list)
if key != None:
a=key
print("Pressed button: "+key)
utime.sleep(0.3)
if a =="1":
duty = degrees_to_duty(35)
pwm.duty_u16(duty)
utime.sleep(0.3)
if a =="4":
duty = degrees_to_duty(65)
pwm.duty_u16(duty)
utime.sleep(0.3)
if a =="7":
duty = degrees_to_duty(100)
pwm.duty_u16(duty)
utime.sleep(0.3)
if a =="D":
duty = degrees_to_duty(135)
pwm.duty_u16(duty)
utime.sleep(0.3)
if a =="0":
duty = degrees_to_duty(0)
pwm.duty_u16(duty)
utime.sleep(0.3)