from machine import Pin, I2C
from machine import sleep
import ssd1306
import machine
from ssd1306 import SSD1306_I2C
from time import sleep
from servo import Servo
from two_axis_analog_joystick import TwoAxisAnalogJoystick

BUTT1 = Pin(25, Pin.IN)
BUTT2 = Pin(26, Pin.IN)
BUTT3 = Pin(27, Pin.IN)


SERVO1 = Servo(pin_id=16)
SERVO2 = Servo(pin_id=17)
SERVO3 = Servo(pin_id=0)

# ESP32 Pin assignment 
i2c = machine.I2C(sda=machine.Pin(21), scl=machine.Pin(22))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

stick = TwoAxisAnalogJoystick(25, 26, 12)

while True:
    val = stick.GetRawCount()
    x = val[0]
    y = val[1]
    x1= str(x)
    y1=str(y)
    print("x count:", x)
    print("y count:", y)
    sleep(0.0005)


    if x == 32776:
        SERVO1.write(90)
        'sleep(0.5)'
        'SERVO1.write(60)'
        'sleep(0.5)'
        'SERVO1.write(90)'

    if x == 65535:
        SERVO1.write(0)
        'sleep(0.5)'
        'SERVO1.write(60)'
        'sleep(0.5)'
        'SERVO1.write(90)'
   
    if x == 0:
        SERVO1.write(180)
        'sleep(0.5)'
        'SERVO1.write(60)'
        'sleep(0.5)'
        'SERVO1.write(90)'
    
    if y == 32776:
        SERVO2.write(90)
        'sleep(0.5)'
        'SERVO1.write(60)'
        'sleep(0.5)'
        'SERVO1.write(90)'

    if y == 65535:
        SERVO2.write(0)
 
    if y == 0:
        SERVO2.write(180)
    

    
    if BUTT3.value == 1:
      SERVO3.write(0)
      'sleep(0.0005)'
      'SERVO3.write(60)'
      'sleep(0.0005)'
      'SERVO3.write(30)'

    if BUTT3.value == 0:
      SERVO3.write(90)
      'sleep(0.0005)'
      'SERVO3.write(60)'
      'sleep(0.0005)'
      'SERVO3.write(30)'
    
    oled.fill(0)
    oled.text('x value=', 0, 0)
    oled.text('y value=', 0, 10)
    oled.text(x1, 70, 0)
    oled.text(y1, 70, 10)
    oled.show()