# ปุ่มหมายเลข 1 เปิด-ปิด relay ตัวที่ 1
# ปุ่มหมายเลข 2 เปิด-ปิด relay ตัวที่ 2
from machine import Pin,I2C
import ssd1306
from time import sleep
import utime
import machine
# GPIO 12,13 Control Relay
relay1 = Pin(12, Pin.OUT)
relay2 = Pin(13, Pin.OUT)
relay1_state = 0
relay2_state = 0
WIDTH = 128
HEIGHT = 64
# I2C 21,22 OLED
i2c = I2C(scl=Pin(22), sda=Pin(21)) #Init i2c
oled=ssd1306.SSD1306_I2C(128,64,i2c,0x3c)
# CONSTANTS
KEY_UP = const(0)
KEY_DOWN = const(1)
keys = [['1', '4', '7', '*'],
['2', '5', '8', '0'],
['3', '6', '9', '#'],
['A', 'B', 'C', 'D']]
# GPIO KEYPAD
cols = [19, 18, 5, 17]
rows = [16, 4, 2, 15]
# set pins for rows as outputs
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]
# set pins for cols as inputs
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]
def init():
for row in range(0,4):
for col in range(0,4):
row_pins[row].value(0)
def scan(row, col):
""" scan the keypad """
# set the current column to high
row_pins[row].value(1)
key = None
# check for keypressed events
if col_pins[col].value() == KEY_DOWN:
key = KEY_DOWN
if col_pins[col].value() == KEY_UP:
key = KEY_UP
row_pins[row].value(0)
# return the key state
return key
print("starting")
# set all the columns to low
init()
while True:
oled.fill(0)
for row in range(4):
for col in range(4):
key = scan(row, col)
if key == KEY_DOWN:
last_key_press = keys[row][col]
oled.text("Key Pressed: ",10,0)
print("Key Pressed", last_key_press)
oled.text(last_key_press, 55, 30) # display the character associated with the key press
oled.show()
if last_key_press == '1':
if relay1_state == 0:
relay1_state = 1
else:
relay1_state = 0
relay1.value(relay1_state)
if last_key_press == '2':
if relay2_state == 0:
relay2_state = 1
else:
relay2_state = 0
relay2.value(relay2_state)