13
#include <drivers/servo/servo.h>
14
#include <drivers/servo/stm32_servo_conf.h>
16
#include <kernel/printk.h>
18
#include <config/board_config.h>
20
static TIM_HandleTypeDef TimHandle;
21
static TIM_OC_InitTypeDef sConfig;
28
static int stm32_pwm_init(void) {
29
CONF_PWM0_CLK_ENABLE_GPIO();
31
GPIO_InitTypeDef PORT;
32
memset(&PORT, 0, sizeof(PORT));
33
PORT.Pin = CONF_PWM0_PIN_TIM_NR;
34
PORT.Pull = GPIO_PULLUP;
35
PORT.Mode = GPIO_MODE_AF_PP;
36
PORT.Speed = GPIO_SPEED_FREQ_HIGH;
37
PORT.Alternate = CONF_PWM0_PIN_TIM_AF;
38
HAL_GPIO_Init(CONF_PWM0_PIN_TIM_PORT, &PORT);
40
CONF_PWM0_CLK_ENABLE_TIM();
41
memset(&TimHandle, 0, sizeof(TimHandle));
43
TimHandle.Instance = CONF_PWM0_TIM_INSTANCE();
44
TimHandle.Init.Prescaler = 72;
45
TimHandle.Init.Period = 20000;
46
TimHandle.Init.ClockDivision = 0;
47
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
48
TimHandle.Init.RepetitionCounter = 0;
49
TimHandle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
51
if (HAL_TIM_PWM_Init(&TimHandle) != HAL_OK) {
52
log_error("Failed to init TIM PWM\n");
56
memset(&sConfig, 0, sizeof(sConfig));
58
sConfig.OCMode = TIM_OCMODE_PWM1;
59
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
60
sConfig.OCFastMode = TIM_OCFAST_DISABLE;
61
sConfig.OCNPolarity = TIM_OCNPOLARITY_HIGH;
62
sConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET;
64
sConfig.OCIdleState = TIM_OCIDLESTATE_RESET;
67
sConfig.Pulse = 10000;
68
if (HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, CONF_PWM0_CHANNEL_CHANNEL_TIM()) != HAL_OK)
70
log_error("Failed to config TIM PWM channel\n");
74
if (HAL_TIM_PWM_Start(&TimHandle, TIM_CHANNEL_1) != HAL_OK) {
75
log_error("Failed to start TIM PWM\n");
88
static int stm32_servo_init(struct servo_dev *dev) {
91
if (stm32_pwm_init()) {
92
log_error("Failed to initialize stm32servo\n");
99
#define SERVO_0 CONF_PWM0_SERVO_POS_LOW
100
#define SERVO_180 CONF_PWM0_SERVO_POS_HIGH
115
static int stm32_servo_set(struct servo_dev *dev, int pos) {
124
pos = SERVO_0 + pos * (SERVO_180 - SERVO_0) / (MAX_POS - MIN_POS);
128
if (HAL_TIM_PWM_ConfigChannel(&TimHandle,
130
CONF_PWM0_CHANNEL_CHANNEL_TIM()) != HAL_OK) {
134
if (HAL_TIM_PWM_Start(&TimHandle, CONF_PWM0_CHANNEL_CHANNEL_TIM()) != HAL_OK) {
141
const static struct servo_ops stm32_servo_ops = {
142
.init = stm32_servo_init,
143
.set_pos = stm32_servo_set,
146
SERVO_DEV_DEF(&stm32_servo_ops, NULL);