STM32F4 控制外接振动马达模块例程

发布时间 2023-03-29 15:56:44作者: 滑稽果

我的公众号目前已搁置(临近注销),所以我将以前所写的文章转移到博客园。

此篇公众号文章创建于 2021-01-02 12:02,内容后期无修改。

通过一个外接振动马达模块,来控制该模块的振动。程序需要创建 motor.hmotor.c 文件。需要修改 main.c 文件。外接振动马达模块的 out 端口接单片机的 F0 端口。

振动马达模块程序

motor.c

# include <sys.h>
# include <motor.h>

// 模块初始化
void motor_Init(void) {
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // 上拉
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOF, &GPIO_InitStructure);
    GPIO_SetBits(GPIOF, GPIO_Pin_0); // F0
}

motor.h

# ifndef MOTOR_H
# define MOTOR_H

void motor_Init(void); // 模块初始化声明

# endif

主程序

main.c

# include <sys.h>
# include <motor.h>
# include <delay.h>

int main(void) {
    delay_init(168); // 程序启动后,先进行延时,等待模块上电完成
    motor_Init();    // 调用振动马达模块初始化程序

    while(1) {
        GPIO_SetBits(GPIOF, GPIO_Pin_0);
        delay_ms(1000); // 延迟 1s

        GPIO_ResetBits(GPIOF, GPIO_Pin_0);
        delay_ms(1000); // 延迟 1s
    }
}

效果

程序启动后,振动马达模块开始振动,且每间隔 1s 振动一次,振动时长持续 1s。