|
| 1 | +group = ESP32::LEDC_LOW_SPEED_MODE |
| 2 | +channel = ESP32::LEDC_CHANNEL_0 |
| 3 | +timer = ESP32::LEDC_TIMER_0 |
| 4 | +resolution = ESP32::LEDC_TIMER_14_BIT |
| 5 | +pin = ESP32::GPIO::GPIO_NUM_4 |
| 6 | +frequency = 50 |
| 7 | + |
| 8 | +# Configure the channel and timer. |
| 9 | +ESP32::LEDC.channel_config(pin, group, timer, channel) |
| 10 | +ESP32::LEDC.timer_config(group, timer, resolution, frequency) |
| 11 | + |
| 12 | +# Using 14-bit PWM @ 50Hz, 0-16383 maps from 0 to 20 milliseconds. |
| 13 | +# Calculate how many microseconds each LSB of duty cycle represents. |
| 14 | +US_PER_BIT = (1000000.0 / frequency) / (2 ** resolution) |
| 15 | + |
| 16 | +# Convert from microseconds to duty cycle. |
| 17 | +def microseconds_to_duty(us) |
| 18 | + (us / US_PER_BIT).round |
| 19 | +end |
| 20 | + |
| 21 | +# This is for a 180 degree MG995 motor. Values will differ for other sweep angles, |
| 22 | +# or continuous rotation servos / ESCs. Values may vary between individual motors. |
| 23 | +# |
| 24 | +# Make sure to connect your servo motor to a separate power source! |
| 25 | +# |
| 26 | +5.times do |
| 27 | + # Send 500us pulses for 2 seconds. Should map to 0 degrees. |
| 28 | + ESP32::LEDC.set_duty(group, channel, microseconds_to_duty(500)) |
| 29 | + ESP32::System.delay(2000) |
| 30 | + |
| 31 | + # Send 2500us pulses for 2 seconds. Should map to 180 degrees. |
| 32 | + ESP32::LEDC.set_duty(group, channel, microseconds_to_duty(2500)) |
| 33 | + ESP32::System.delay(2000) |
| 34 | +end |
| 35 | + |
| 36 | +# Turn it off. |
| 37 | +ESP32::LEDC.set_duty(group, channel, 0) |
0 commit comments