Skip to content

Instantly share code, notes, and snippets.

@Fonger
Last active July 6, 2023 09:42
Show Gist options
  • Save Fonger/4f415822bb593c15c2a41fc29335f2e0 to your computer and use it in GitHub Desktop.
Save Fonger/4f415822bb593c15c2a41fc29335f2e0 to your computer and use it in GitHub Desktop.
Servo Control for SG90 (0 to 180 degree) Example using esp-open-rtos
// Servo Control for SG90 (0 to 180 degree)
// MIT License Fonger
// Connect signal pin to NodeMCU D7 (GPIO13)
// add EXTRA_COMPONENTS = extras/pwm to makefile
#include <stdio.h>
#include <FreeRTOS.h>
#include <esp/uart.h>
#include <esp8266.h>
#include <task.h>
#include <pwm/pwm.h>
inline uint16_t get_servo_duty_cycle(double angle) {
if (angle > 180) return -1;
return (uint16_t)((0.025 + (0.12 - 0.025) * (angle / 180.0)) *
(double)UINT16_MAX);
}
void servo_task(void *arg) {
uint8_t pins[1];
printf("pwm_init(1, [13])\n");
pins[0] = 13; // D7 GPIO13
pwm_init(1, pins, false);
printf("pwm_set_freq(50) # 50Hz\n");
pwm_set_freq(50);
pwm_start();
while (true) {
for (int i = 0; i <= 180; i++) {
pwm_set_duty(get_servo_duty_cycle(i));
vTaskDelay(10 / portTICK_PERIOD_MS);
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
for (int i = 180; i >= 0; i--) {
pwm_set_duty(get_servo_duty_cycle(i));
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
}
void user_init(void) {
uart_set_baud(0, 115200);
xTaskCreate(servo_task, "Servo Task", 4096, NULL, tskIDLE_PRIORITY, NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment