stm32f103c8t6按键控制舵机
时间: 2023-05-24 15:06:27 浏览: 211
源码 7、stm32单片机之模拟按键控制单个舵机.zip
5星 · 资源好评率100%
以下是通过按键控制舵机的STM32F103C8T6代码示例,假设使用PA0号口连接按键,PB0号口连接舵机信号引脚:
```c
#include "stm32f10x.h"
#define SERVO_PIN GPIO_Pin_0
#define SERVO_PORT GPIOB
#define BUTTON_PIN GPIO_Pin_0
#define BUTTON_PORT GPIOA
void GPIO_Configuration(void);
void TIM_Configuration(void);
int main(void)
{
GPIO_Configuration();
TIM_Configuration();
while(1)
{
if(GPIO_ReadInputDataBit(BUTTON_PORT, BUTTON_PIN) == 0) //按键按下
TIM_SetCompare1(TIM3, 50); //舵机转动到0度
else //按键松开
TIM_SetCompare1(TIM3, 250); //舵机转动到180度
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//配置PB0引脚为推挽输出,控制舵机转动
GPIO_InitStructure.GPIO_Pin = SERVO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(SERVO_PORT, &GPIO_InitStructure);
//配置PA0引脚为输入,接入按键
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(BUTTON_PORT, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitStruct.TIM_Prescaler = 71; //定时器分频值
TIM_TimeBaseInitStruct.TIM_Period = 19999; //计数器计数上限
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse = 250; //初始占空比,舵机转动到180度
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);
TIM_Cmd(TIM3, ENABLE);
}
```
注:以上代码未包含头文件等内容,需要根据实际情况自行添加。
阅读全文