找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

帖子
查看: 1420|回復(fù): 0
收起左側(cè)

STM32單片機(jī)PWM驅(qū)動電機(jī)程序

[復(fù)制鏈接]
ID:1090286 發(fā)表于 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. }
復(fù)制代碼

原理圖: 無
仿真: 無
代碼: PWM驅(qū)動直流電機(jī).7z (176.85 KB, 下載次數(shù): 22)

回復(fù)

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機(jī)教程網(wǎng)

快速回復(fù) 返回頂部 返回列表