SG90 Servo
IMPORTANT
In many computers the current is not enough to drive the servo!!!
If it does not work, keeps disconnecting, or rebooting the ESP the power is not sufficent and you need an extra power supply.
Schematic - Connecting the SG90
Code Examples ESP8266
Basic control
Assumin the servo is connected to Pin 5.
from machine import Pin,PWM
from time import sleep
servoPin = Pin(5, Pin.OUT)
pwm = PWM(servoPin, freq=50)
pwm.deinit() // workaround to reset PWM
pwm = PWM(servoPin, freq=50)
val = 50
while True:
pwm.duty(val)
val = val + 1
if val>100:
val = 50
print(val)
sleep(0.05)
Controlling the servo with a Poti
A0 is the analog input with 10 bit resolution. It reads the analog value every second and print it to the console and sets the servo based on the analog input.
from machine import Pin, ADC, PWM
from time import sleep
analogPin = ADC(0)
servoPin = Pin(5, Pin.OUT)
pwm = PWM(servoPin, freq=50)
pwm.deinit()
pwm = PWM(servoPin, freq=50)
while True:
analogVal = analogPin.read()
pwm.duty(int(analogVal/10))
print(analogVal)
sleep(1)