使用arduino uno控制两个直流电机

时间:2014-05-12 10:22:25

标签: arduino motordriver

所以我使用这个示例代码运行我的两个电机...但代码仅适用于一个电机...如何修改此代码以使其他电机工作?我尝试用频道b替换频道a,但由于某种原因没有用?

const int channel_a_enable  = 6;
const int channel_a_input_1 = 4;
const int channel_a_input_2 = 7;
const int channel_b_enable  = 5;
const int channel_b_input_3 = 3;
const int channel_b_input_4 = 2;

void setup()
{
  pinMode( channel_a_enable, OUTPUT );  // Channel A enable
  pinMode( channel_a_input_1, OUTPUT ); // Channel A input 1
  pinMode( channel_a_input_2, OUTPUT ); // Channel A input 2

  pinMode( channel_b_enable, OUTPUT );  // Channel B enable
  pinMode( channel_b_input_3, OUTPUT ); // Channel B input 3
  pinMode( channel_b_input_4, OUTPUT ); // Channel B input 4

  Serial.begin( 38400 );
  Serial.println("Starting up");
}

void loop()
{
      Serial.println("Channel A forward");
      analogWrite( channel_a_enable, 255);
      digitalWrite( channel_a_input_1, HIGH);
      digitalWrite( channel_a_input_2, LOW);
      delay(5000);
      allInputsOff();

      Serial.println("Channel A reverse");
      analogWrite( channel_a_enable, 255);
      digitalWrite( channel_a_input_1, LOW);
      digitalWrite( channel_a_input_2, HIGH);
      delay(5000);
      allInputsOff();

      Serial.println("Channel A forward half speed");
      analogWrite( channel_a_enable, 127);
      digitalWrite( channel_a_input_1, HIGH);
      digitalWrite( channel_a_input_2, LOW);
      delay(5000);
      allInputsOff();
}

void allInputsOff()
{
  digitalWrite( 4, LOW );
  digitalWrite( 7, LOW );
  digitalWrite( 6, LOW );
  digitalWrite( 3, LOW );
  digitalWrite( 2, LOW );
  digitalWrite( 5, LOW );
}

1 个答案:

答案 0 :(得分:0)

您的演示代码仅引用频道' a'除了设置。

这是一个片段,展示了如何打开两个电机:

Serial.println("Channels A and B forward");
analogWrite( channel_a_enable, 255);
digitalWrite( channel_a_input_1, HIGH);
digitalWrite( channel_a_input_2, LOW);
analogWrite( channel_b_enable, 255);
digitalWrite( channel_b_input_3, HIGH);
digitalWrite( channel_b_input_4, LOW);
delay(5000);
allInputsOff();

当然,每个电机的代码几乎相同,因此您可以创建一个子程序:

void runMotor(int enablePin, int input1, int input2) {
    analogWrite( enablePin, 255);
    digitalWrite( input1, HIGH);
    digitalWrite( input2, LOW);
}

然后像这样使用它:

Serial.println("Channels A and B forward");
runMotor(channel_a_enable, channel_a_input_1, channel_a_input_2);
runMotor(channel_b_enable, channel_b_input_3, channel_b_input_4);
delay(5000);
allInputsOff();

免责声明:我在午休时间而不是在Arduino IDE中写这个,所以可能会有一些小错误。