# =============================
# GRAY OLED KEYBOARD AI
# SH1107 + JOYSTICK + WIFI
# =============================
import network, urequests, time
from machine import Pin, ADC, I2C
import sh1107
# ------- WIFI CONFIG ----------
SSID = "YOUR_WIFI"
PASS = "YOUR_PASSWORD"
AI_URL = "https://your-ai-server.com/api"
# ------- I2C + OLED ------------
i2c = I2C(1, scl=Pin(7), sda=Pin(6))
oled = sh1107.SH1107_I2C(128, 128, i2c)
# ------- JOYSTICK --------------
joy_x = ADC(Pin(2))
joy_y = ADC(Pin(4))
joy_btn = Pin(1, Pin.IN, Pin.PULL_UP)
# ------- KEYBOARD MAP ----------
keys = [
["A","B","C","D"],
["E","F","G","H"],
["I","J","K","L"],
["SPACE","DEL","SEND"]
]
row = 0
col = 0
text = ""
# ------- WIFI CONNECT ----------
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASS)
while not wlan.isconnected():
time.sleep(0.2)
print("WiFi OK:", wlan.ifconfig())
wifi_connect()
# ------- DRAW UI ---------------
def draw_ui():
oled.fill(0)
oled.text("GRAY AI KEYPAD", 0, 0)
y = 20
for r in range(len(keys)):
line = ""
for c in range(len(keys[r])):
k = keys[r][c]
if r == row and c == col:
line += "[" + k + "] "
else:
line += " " + k + " "
oled.text(line, 0, y)
y += 20
oled.text("TEXT:", 0, 100)
oled.text(text[-12:], 0, 112) # hiển thị 12 ký tự cuối
oled.show()
# ------- READ JOYSTICK ----------
def read_joy():
global row, col
x = joy_x.read_u16()
y = joy_y.read_u16()
# lên
if y < 10000:
row = max(0, row - 1)
time.sleep(0.2)
# xuống
if y > 55000:
row = min(len(keys)-1, row + 1)
time.sleep(0.2)
# trái
if x < 10000:
col = max(0, col - 1)
time.sleep(0.2)
# phải
if x > 55000:
col = min(len(keys[row])-1, col + 1)
time.sleep(0.2)
# ------- AI SEND ---------------
def send_ai(text):
try:
r = urequests.post(AI_URL, json={"msg": text})
reply = r.text
r.close()
return reply
except:
return "ERROR"
# ------- MAIN LOOP -------------
while True:
draw_ui()
read_joy()
# ấn nút joystick
if not joy_btn.value():
k = keys[row][col]
if k == "DEL":
text = text[:-1]
elif k == "SPACE":
text += " "
elif k == "SEND":
oled.fill(0)
oled.text("Sending...", 0, 0)
oled.show()
ans = send_ai(text)
text = ans # show AI trả lời
time.sleep(0.5)
else:
text += k
time.sleep(0.25)
import network, time
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
print("Đang kết nối WiFi...")
while not wifi.isconnected():
time.sleep(0.1)
print("Đã kết nối!")
print("IP:", wifi.ifconfig())
# bắt đầu từ line 110
...
# kết thúc line 150
Loading
grove-oled-sh1107
grove-oled-sh1107