找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 1388|回复: 0
打印 上一主题 下一主题
收起左侧

STM32单片机PWM驱动电机程序

[复制链接]
跳转到指定楼层
楼主
ID:1090286 发表于 2023-10-21 13:44 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#include "stm32f10x.h"                  // Device header
#include "PWM.h"

void Motor_Init(void)
{
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
        
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_Init(GPIOA, &GPIO_InitStructure);
        
        PWM_Init();
}

void Motor_SetSpeed(int8_t Speed)
{
        if (Speed >= 0)
        {
                GPIO_SetBits(GPIOA, GPIO_Pin_4);
                GPIO_ResetBits(GPIOA, GPIO_Pin_5);
                PWM_SetCompare3(Speed);
        }
        else
        {
                GPIO_ResetBits(GPIOA, GPIO_Pin_4);
                GPIO_SetBits(GPIOA, GPIO_Pin_5);
                PWM_SetCompare3(-Speed);
        }
}

  1. #include "stm32f10x.h"                  // Device header
  2. #include "Delay.h"
  3. #include "OLED.h"
  4. #include "Motor.h"
  5. #include "Key.h"

  6. uint8_t KeyNum;
  7. int8_t Speed;

  8. int main(void)
  9. {
  10.     OLED_Init();
  11.     Motor_Init();
  12.     Key_Init();
  13.    
  14.     OLED_ShowString(1, 1, "Speed:");
  15.    
  16.     while (1)
  17.     {
  18.         KeyNum = Key_GetNum();
  19.         if (KeyNum == 1)
  20.         {
  21.             Speed += 20;
  22.             if (Speed > 100)
  23.             {
  24.                 Speed = -100;
  25.             }
  26.         }
  27.         Motor_SetSpeed(Speed);
  28.         OLED_ShowSignedNum(1, 7, Speed, 3);
  29.     }
  30. }
复制代码

原理图: 无
仿真: 无
代码: PWM驱动直流电机.7z (176.85 KB, 下载次数: 22)

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享淘帖 顶 踩
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表