arduino控制直流电机

一、实物连接

在这里插入图片描述

二、代码实现


const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin
const int motorIn1 = 9;
const int motorIn2 = 10;
int stat = 0; 
#define rank1 150
#define rank2 200
#define rank3 250
// Variables will change:
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
/******************************************************************************/
void setup() 
{
  //set theled,motors as OUTPUT,button as INPUT
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  pinMode(motorIn1,OUTPUT);
  pinMode(motorIn2,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState)// If the button state is different from last time 
  {   
    lastDebounceTime = millis();// reset the debouncing timer
  } 
  if ((millis() - lastDebounceTime) > debounceDelay) 
  { 
    if (reading != buttonState) 
    {
      buttonState = reading; // Store the state of button in buttonState 
      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH)
      {
        digitalWrite(ledPin, HIGH); //turn on the LED
        stat = stat + 1;
        if(stat >= 4)// When stat>=4, set it as 0. 
        {
          stat = 0;
        }
      }
      else
        digitalWrite(ledPin, LOW);
    }
  } 
  switch(stat)
  {
  case 1:
    clockwise(rank1);// When stat=1, set the rotate speed of the motor as rank1=150
    break;
  case 2:
    clockwise(rank2);// When stat=2, set the rotate speed of the motor as rank1=200
    break;
  case 3:
    clockwise(rank3);// When stat=3, set the rotate speed of the motor as rank1=250
    break;
  default:
    clockwise(0);// else, set the rotate speed of the motor as rank1=150
  }
  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}
/***********************************************************/
void clockwise(int Speed)//
{
  analogWrite(motorIn1,0);
  analogWrite(motorIn2,Speed);
}
/***********************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gcc future.c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值