import utime
import ssd1306
import machine
import gfx
import math
i2c=machine.I2C(0,sda=machine.Pin(0), scl=machine.Pin(1), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
oled_width = 128
oled_height = 64
graphics = gfx.GFX(oled_width, oled_height, oled.pixel)
analog_value = machine.ADC(26)
  
# Set up PWM Pin for servo control
servo_pin = machine.Pin(22)
servo = machine.PWM(servo_pin)
#Set PWM frequency
frequency = 50
servo.freq (frequency)
while True:
  pot_value = analog_value.read_u16()
  print(pot_value)
  #servo.duty_u16(pot_value)
  servo.duty_u16(int(pot_value/6.8)) #6.8 by trying
  
 
  converted_val = str(pot_value) 
  oled.fill(0)
  #oled.text("Value: " + converted_val, 0, 55)
  
  graphics.circle(64, 24, 24, 1) #(x0, y0, radius, color)
  #line under construction ;)
  w = ((pot_value / 65535) * 360) - 180  # achtung "-180" damit 'Startausrichtung' stimmt
  wo = int(w)
  winkel = str(wo)
  wr = w * (math.pi/180) #achtung, muss in rad (radiant) umgerechnet werden damit punktberechnung unten klappt
  X0 = 64
  Y0 = 24
  xp = X0 + (24 * math.cos(wr)) 
  yp = Y0 + (24 * math.sin(wr))
  x1 = int(xp)
  y1 = int(yp)
  graphics.line(X0, Y0, x1, y1, 1)
  oled.text("Winkel: " + winkel, 0, 55)
  #graphics.line(64, 24, 127, 24, 1) #(x0, y0, x1, y1, color) // x0,y0 start of line // x1,y1 end of line
  oled.show()
  
  utime.sleep(0.05)