伺服器无法正确移动

时间:2019-11-22 09:01:57

标签: c++ bluetooth arduino-uno hc-05

这是我的代码:

#include <SoftwareSerial.h>
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
Servo servo2;
Servo servo3;
SoftwareSerial bluetooth(5, 6); // RX, TX
int servo1Pin = 11;
int servo2Pin = 10;
int servo3Pin = 9;
int motor1pin = 8;
int flag = 0; //Sets integer for HIGH or LOW LED case
String bdata = "";
char c = ' ';

void setup()
{
  bluetooth.begin(9600);
  pinMode(motor1pin, OUTPUT);
  servo1.attach(servo1Pin);
  servo2.attach(servo2Pin);
  servo3.attach(servo3Pin);
}

void loop()
{
  int position;
  while (bluetooth.available()) {
    c = bluetooth.read();
    bdata += c;

    //~~~~~~Servo 1~~~~~~~~
    if (bdata == "open1")
    {
      //Opens Door
      for (position = 0; position < 90; position += 1)
      {
        servo1.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }
    if (bdata == "close1")
    {
      //Closes Door
      for (position = 90; position >= 0; position -= 1)
      {
        servo1.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }
    //~~~~~~Servo 2~~~~~~~~
    if (bdata == "open2")
    {
      //Opens Door
      for (position = 0; position < 90; position += 1)
      {
        servo2.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }
    if (bdata == "close2")
    {
      //Closes Door
      for (position = 90; position >= 0; position -= 1)
      {
        servo2.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }

    //~~~~~~Servo 3~~~~~~~~
    if (bdata == "open3")
    {
      //Opens Door
      for (position = 0; position < 90; position += 1)
      {
        servo3.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }
    if (bdata == "close3")
    {
      //Closes Door
      for (position = 90; position >= 0; position -= 1)
      { 

        servo3.write(position);  // Move to next position
        delay(20);               // Short pause to allow it to move
      }
    }
    //~~~~~~Motor 1~~~~~~
      if (bdata == "on")
    {
      flag = 1; //Turns LEDs on using a high digital signal
    }
    if (bdata == "off")
    {
      flag = 0; //Turns LEDs off using a low digital signal
    }

  }
  digitalWrite(motor1pin, flag);
  delay(1000);
  bdata = "";
}

它被上传到Arduino Uno,在那里我通过面包板连接了3个伺服器和DC电动机。它旨在为我制作的3D打印机械臂提供动力。阅读时,您可以看到它也通过使用HC-05模块和电话通过蓝牙进行控制。我遇到了麻烦,因为伺服1的命令可以正常工作,所以3可以正常工作,但是当从电话发送伺服2的命令时,伺服3移动了,而伺服3的命令也移动了伺服3。我已经尝试过查看变量手机上的命令什么也没显示出来。所以我在这里。 有人可以帮忙吗?

0 个答案:

没有答案