import network
import urequests
from machine import Pin, ADC, I2C
import time
import ssd1306
# I2C OLED ayarları
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
FIREBASE_URL = 'https://snake-5b1df-default-rtdb.firebaseio.com/.json'
def printText(text):
oled.fill(0)
oled.text(text, 10, 20)
oled.show()
printText("Yukleniyor...")
def get_direction():
try:
response = urequests.get(FIREBASE_URL)
data = response.json()
response.close()
return data.get("direction", "N/A")
except Exception as e:
print("Firebase bağlantı hatası:", e)
return "N/A"
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
print("Bağlanıyor...")
time.sleep(1)
print("Bağlandı:", wlan.ifconfig())
printText(get_direction())
def update_direction(direction):
url = FIREBASE_URL
headers = {"Content-Type": "application/json"}
data = '{"direction": "' + direction + '"}'
response = urequests.put(url, data=data, headers=headers)
response.close()
printText(direction)
print("Yön güncellendi:", direction)
# Joystick pinleri ayarla
joystick_x = ADC(Pin(26)) # X ekseni (ADC0)
joystick_y = ADC(Pin(27)) # Y ekseni (ADC1)
button_pin = Pin(22, Pin.IN, Pin.PULL_UP) # Joystick butonu
# Joystick'i kontrol etme fonksiyonu
def check_joystick():
x_value = joystick_x.read_u16() # 16 bit okuma
y_value = joystick_y.read_u16() # 16 bit okuma
# Joystick'i X ve Y eksenlerine göre kontrol et
if x_value < 1000: # X ekseni sola hareket
update_direction("left")
time.sleep(0.5) # Debounce süresi
elif x_value > 60000: # X ekseni sağa hareket
update_direction("right")
time.sleep(0.5) # Debounce süresi
if y_value < 1000: # Y ekseni yukarı hareket
update_direction("up")
time.sleep(0.5) # Debounce süresi
elif y_value > 60000: # Y ekseni aşağı hareket
update_direction("down")
time.sleep(0.5) # Debounce süresi
# Buton kontrolü
if not button_pin.value(): # Joystick butonuna basılmışsa
print("button pressed")
time.sleep(0.5) # Debounce süresi
connect_wifi()
try:
while True:
check_joystick()
time.sleep(0.1)
except KeyboardInterrupt:
print("Program durduruldu.")