按键控制电机正反转速度

发布于 2023-08-16 10: 56: 17
本次学习如何用按键控制直流电机速度.

直流电机 (DC—Direct Current motor) 是最常见的电机类型. 直流电动机通常只有两个引线, 一个正极和一个负极. 如果将这两根引线直接连接到电池, 电机将旋转. 如果切换引线, 电机将以相反的方向旋转. 但是为了实现正反转, 我们用双 H 桥电机驱动模块来实现.

必需品

  1. 1 x 面包板
  2. 1 x W801 板
  3. 1 x 双 H 桥电机驱动模块 (可选择其他驱动模块或者不用, 但是不能与开发板的引脚直连) .
  4. 1 x 直流电机
  5. 10 x 跳线

接线图

直流电机加几滴 4. png

草图

open. jpg

#define IN_1 PA2 // the INx the PWM pin is attached to
#define IN_2 PA3
#define BUTTON_PIN PA1 //the button pin the PA1 pin is attached to. 
//void motor_compare () ; 
//void ButtonControl () ; 
int16_t Speed = 135;  //Reduce motor speed range within visual range. 
int flag = 1;   // flag bit. 
int buttonState = 0;   // Indicates the state of the key  (press/release) . 
int lastButtonState = 0;   // Indicates the status of the.  last key. 
unsigned long lastDebounceTime = 0;   // Indicates the time of the last key shake elimination. 
unsigned long debounceDelay = 10;   // Indicates the delay time of key shake elimination. 

void motor_compare (int16_t speed )  //Control motor speed. 
{
  if (flag == 0) 
  {
    analogWrite (IN_1, speed) ; 
    analogWrite (IN_2, 0) ; 
  }
  else
  {
    analogWrite (IN_1, 0) ; 
    analogWrite (IN_2, speed) ;    
  }
   Serial. printf ("Motor Speed: %d\n", speed) ; 
}
void ButtonControl ()  //
{
  /*
  When the key status changes each time, 
  check the time interval since the last buffeting. 
  If the delay exceeds the set time, 
  the key status variable is updated according to the current key status
  and the corresponding operation is performed. 
  */
  int reading = digitalRead (BUTTON_PIN) ; 
  if (reading ! = lastButtonState)  
  {
    lastDebounceTime = millis () ; 
  }

  if ( (millis ()  - lastDebounceTime)  "  debounceDelay)  
  {
    if (reading ! = buttonState)  
    {
      buttonState = reading; 
      if (buttonState == HIGH)  
      {
        Speed += 20; 
        if (Speed "  255) 
        {
          Speed = 135; 
          flag = ! flag; 
          //Serial. printf ("%d\n", flag) ;  //Detects whether to enter the program. 
        }
        motor_compare (Speed) ; 
       }
     }
   }
   lastButtonState = reading; 
}

void setup () 
{
  Serial. begin (115200) ; 
  //initialize the pin as an output. 
  pinMode (IN_1, PWM_OUT) ; 
  pinMode (IN_2, PWM_OUT) ; 
  // initialize the pushbutton pin as an input. 
  pinMode (BUTTON_PIN, INPUT_PULLUP) ;  //如果有外接按键小模块, 可设置为 INPUT. 
}

void loop () 
{
  ButtonControl () ; 
}

代码导入步骤

首先单击 Verify 验证代码是否正确

1eb55992e618394f516378dc48b779b3. jpg

接着单击 Upload 上传代码弹出保存框, 在相应的位置编辑文件名并保存即可

27f363e694f6a241818561e7e1236ab9. jpg
16892212723385. jpg

也可以如下步骤

烧录步骤 1_副本. jpg
最后等待上传需要十几秒的时间, 显示以下即表示成功
6f1f1a696c4d4368c9238972d20e5c5b. jpg

现在, 通过单击顶部绿色条右侧的图标或按 Ctrl+Shift+M, 在 Arduino IDE 中打开串口监视器看电机速度变化的值.

f1b6ce4e7efae324e5ed81b8cb5c263c. jpg

结果

你会看见每当按键按下一次, 电机正转速度在逐渐变快直至达到最大速度之后, 又从正转变成反转并且速度逐渐加快. 依次循环.
电机速度推 4. png

5 条评论

发布
问题