STM32-SERVO-MOTOR-Initialization

by Marwen Maghrebi
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private define ------------------------------------------------------------*/
// Button definitions
#define BTN_45_PIN  GPIO_PIN_0
#define BTN_90_PIN  GPIO_PIN_1
#define BTN_N45_PIN GPIO_PIN_2
#define BTN_N90_PIN GPIO_PIN_3
#define BTN_PORT    GPIOB

/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim2;
int16_t currentAngle = 0;  // Start at 90 degrees

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_TIM2_Init(void);

/* USER CODE BEGIN 0 */
void SetServoAngle(int16_t angle) {
    /* Ensure angle is within valid range */
    if (angle < 0) angle = 0;
    if (angle > 180) angle = 180;

    /* Calculate pulse width in microseconds */
    uint32_t pulse = (angle * 1000) / 180 + 1000; // Calculate pulse width in microseconds
    __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, pulse); // Set the PWM pulse width for the servo

    currentAngle = angle;  // Update current angle
}
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00