基于stm32,航模遥控器SBUS协议,控制L29N电机驱动
时间: 2024-01-25 11:48:40 浏览: 71
基于STM32的航模遥控器可以通过SBUS协议来接收来自遥控器的信号,然后通过PWM信号控制L29N电机驱动模块。下面是一个简单的代码示例:
```c
#include "stm32f1xx_hal.h"
#include "stdio.h"
#include "stdlib.h"
#define SBUS_BUFFER_SIZE 25
#define PWM_MIN 1000
#define PWM_MAX 2000
#define PWM_MID 1500
UART_HandleTypeDef huart1;
uint8_t sbus_buffer[SBUS_BUFFER_SIZE];
uint16_t sbus_channels[18];
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
static uint8_t buffer_index = 0;
if (huart->Instance == USART1) {
if (buffer_index == 0 && sbus_buffer[0] != 0x0F) {
return;
}
sbus_buffer[buffer_index++] = huart->Instance->DR;
if (buffer_index == SBUS_BUFFER_SIZE) {
buffer_index = 0;
for (uint8_t i = 0; i < 16; i++) {
uint16_t value = sbus_buffer[1 + 2 * i] + (sbus_buffer[2 + 2 * i] << 8);
sbus_channels[i] = (value > PWM_MAX) ? PWM_MAX : (value < PWM_MIN) ? PWM_MIN : value;
}
}
}
HAL_UART_Receive_IT(&huart1, &sbus_buffer[buffer_index], 1);
}
int main(void) {
HAL_Init();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_USART1_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
huart1.Instance = USART1;
huart1.Init.BaudRate = 100000;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart1);
HAL_UART_Receive_IT(&huart1, sbus_buffer, 1);
TIM_HandleTypeDef htim3;
__HAL_RCC_TIM3_CLK_ENABLE();
htim3.Instance = TIM3;
htim3.Init.Prescaler = 71;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 19999;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_PWM_Init(&htim3);
TIM_OC_InitTypeDef sConfigOC = {0};
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = PWM_MID;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
while (1) {
uint16_t throttle = sbus_channels[2];
if (throttle > PWM_MAX) {
throttle = PWM_MAX;
} else if (throttle < PWM_MIN) {
throttle = PWM_MIN;
}
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, throttle);
}
}
```
这个代码示例中,我们使用了STM32的UART模块来接收来自遥控器的SBUS信号,并将其解析为PWM信号。然后,我们使用STM32的定时器模块来生成PWM信号,并通过L29N电机驱动模块将其输出到电机。在主循环中,我们不断地读取油门通道的PWM值,并将其输出到电机。注意,这个示例中只控制了一个电机,如果需要控制多个电机,需要使用更多的PWM输出通道。