野火电子论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9671|回复: 3

STM32控制28BYJ-48电机

[复制链接]
发表于 2018-4-28 19:21:27 | 显示全部楼层 |阅读模式
最近在学用STM32控制步进电机(小白,刚入手STM32)这是我根据网上的程序写成的:

#include "stm32f10x.h"
#include "stm32f10x_gpio.h"

uint8_t phasecw[8]={0x08,0x0c,0x04,0x06,0x02,0x03,0x01,0x09} ;  //正转
uint8_t phaseccw[8]={0x09,0x01,0x03,0x02,0x06,0x04,0x0c,0x08} ;  //反转

void delay_us()/*延迟函数*/
{
    unsigned int i = 20;
    while (i--);
}


void Step_Motor_GPIO_Init(void) /*初始化引脚,PB2,PB3,PB4,PB5*/
{
  GPIO_InitTypeDef GPIO_InitStruct;         
        /* 配置RCC寄存器 */
        *(unsigned int *)0X40021018 |= (1<<3);
       
        GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5;
        GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHZ;
        GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
        GPIO_Init(GPIOB,&GPIO_InitStruct);
       
}

void SetMotor(unsigned char InputData) /*引脚映射*/
{
    if(InputData&0x08)
    {
        GPIO_ResetBits(GPIOB,GPIO_Pin_2);   
    }
    else
    {
        GPIO_SetBits(GPIOB,GPIO_Pin_2);
    }
    if(InputData&0x04)
    {
        GPIO_ResetBits(GPIOB,GPIO_Pin_3);   
    }
   else
    {
        GPIO_SetBits(GPIOB,GPIO_Pin_3);
    }
    if(InputData&0x02)
    {
        GPIO_ResetBits(GPIOB,GPIO_Pin_4);   
    }
    else
    {
        GPIO_SetBits(GPIOB,GPIO_Pin_4);
    }
   if(InputData&0x01)
    {
       GPIO_ResetBits(GPIOB,GPIO_Pin_5);   
    }
   else
    {
       GPIO_SetBits(GPIOC, GPIO_Pin_5);
    }
}


void motorNCircle(int n,int x) /*n为圈数,position代表正反转,这里1正转,0反转*/
{
   int i=0;
   int j=0;
   int k=0;
   for(j=0;j<n;j++)
   {
      for(i=0;i<64*8;i++)     
      {
          for(k=0;k<8;k++)
          {
              if(x>=1)
                 SetMotor(phasecw[k]);  
             else
                 SetMotor(phaseccw[k]);  
             delay_us();      
          }
      }
    }
}

int main(void)
{
         unsigned int b;
   Step_Motor_GPIO_Init();
         while(1)
  {
     motorNCircle(3,0);
  }
}




void SystemInit(void)
{
        /*让编译器不报错 */
}



但是电机只听得到嗡嗡嗡的声音,并不转,想问一下各位,程序的问题出在了哪里?
微信图片_20180428191420.jpg
回复

使用道具 举报

发表于 2018-4-29 09:22:33 | 显示全部楼层
延时有点短,我手里的测试延时低于一毫秒就转不起来。你可以增加延时试试。可以用个定时器来控制呀。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-5-2 15:05:13 | 显示全部楼层
木森林的年轮 发表于 2018-4-29 09:22
延时有点短,我手里的测试延时低于一毫秒就转不起来。你可以增加延时试试。可以用个定时器来控制呀。

好的 谢谢 增加延时之后确实可以正常运行了
回复 支持 反对

使用道具 举报

发表于 2018-5-2 18:38:20 | 显示全部楼层
Pdogg 发表于 2018-5-2 15:05
好的 谢谢 增加延时之后确实可以正常运行了

可以尝试用定时器来控制速度,比延时效率高一些。
回复 支持 反对

使用道具 举报

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

本版积分规则

联系站长|手机版|野火电子官网|野火淘宝店铺|野火电子论坛 ( 粤ICP备14069197号 ) 大学生ARM嵌入式2群

GMT+8, 2024-5-3 02:55 , Processed in 0.031771 second(s), 26 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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