Untitled

mail@pastecode.io avatar
unknown
plain_text
14 days ago
2.0 kB
1
Indexable
Never
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"
#include "esp_err.h"

// Function to control the servo motor
void controlServo(int speed, float rotation_time) {
    int angle = (speed * 180) / 100; // Convert speed to angle

    // Calculate the duty cycle for the given angle
    // Assuming 0° corresponds to 2.5% duty cycle and 180° corresponds to 12.5% duty cycle
    float duty_cycle = (angle / 18.0) + 2.5;

    // Convert duty cycle to a value between 0 and 2^LEDC_TIMER_13_BIT-1
    int duty = (int)(duty_cycle * ((1 << LEDC_TIMER_13_BIT) - 1) / 100);

    // Set the duty cycle for the PWM channel
    ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, duty);
    ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0);

    // Wait for half of the rotation time
    vTaskDelay(pdMS_TO_TICKS((rotation_time / 2) * 1000));

    // Stop the servo by setting the duty cycle to 0
    ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0);
    ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0);
}

void app_main() {
    // Configure the timer for PWM
    ledc_timer_config_t ledc_timer = {
        .speed_mode       = LEDC_HIGH_SPEED_MODE,
        .duty_resolution  = LEDC_TIMER_13_BIT,
        .timer_num        = LEDC_TIMER_0,
        .freq_hz          = 50,  // Servo motors typically use 50 Hz frequency
        .clk_cfg          = LEDC_AUTO_CLK
    };
    ledc_timer_config(&ledc_timer);

    // Configure the PWM channel
    ledc_channel_config_t ledc_channel = {
        .speed_mode     = LEDC_HIGH_SPEED_MODE,
        .channel        = LEDC_CHANNEL_0,
        .timer_sel      = LEDC_TIMER_0,
        .intr_type      = LEDC_INTR_DISABLE,
        .gpio_num       = 18,  // GPIO pin for PWM output
        .duty           = 0,   // Initial duty cycle
        .hpoint         = 0
    };
    ledc_channel_config(&ledc_channel);

    // Example usage of controlServo function
    controlServo(50, 1.0);  // Rotate the servo motor to 90 degrees over 1 second
}
Leave a Comment