180和360舵机

写了半天,贴代码的时候崩溃了,不想写了。记几个关键点:
1.360度舵机中 servo.write(90);//90代表的不是角度,而是速度和方向。90刚好是中间值,所以是停止。servo.write(80).逆时针10的速度转。servo.write(100);顺时针10的速度旋转
2.180度舵机 servo.write(90);让舵机转到90度的位置。
3.外接电源用台式机的5v输出功率未知够不够,但是能转起来。
4.使用Servo.h库控制多路舵机(三个),arduino可以控制180度的三个,但是360度的控制不了,只能控制两个,测试舵机是MG995

        #include
Servo base,fArm,rArm,claw;
int DSD=15;

void setup() {
  // put your setup code here, to run once:
  base.attach(11);
  delay(200);
  fArm.attach(10);
  delay(200);
  rArm.attach(9);
  delay(200);
  base.write(90);
  fArm.write(90);
  rArm.write(90);

 Serial.begin(9600);
 Serial.println("机械臂舵机测试程序现在开始:");
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available()>0){
      char serialCmd=Serial.read();
      armDataCmd(serialCmd);
    }
}
void armDataCmd(char serialCmd){
    if(serialCmd=='b'||serialCmd=='c'||serialCmd=='f'||serialCmd=='r'){
      int servoData=Serial.parseInt();
      servoCmd(serialCmd,servoData,DSD);
     }else{
        switch(serialCmd){
            case'o':
              reportStatus();
              break;
             default:
                Serial.println("Unknown Command.");
          }     
      }
  }

  void servoCmd(char servoName,int toPos,int servoDelay){
      Servo servo2go;
      Serial.println("-------------------------");
      Serial.print("+Commadn:servo");
      Serial.print(servoName);
      Serial.print("to");
      Serial.print(toPos);
      Serial.print("at servoDelay value:");
      Serial.print(servoDelay);
      Serial.println(".");
      Serial.print("----------------------------");

      int fromPos;
      switch(servoName){
          case 'b':
            servo2go=base;
            fromPos=base.read();
            break;
          case 'f':
            servo2go=fArm;
            fromPos=fArm.read();
            break;
          case 'r':
            servo2go=rArm;
            fromPos=rArm.read();
            break;
          case 'c':
            servo2go=claw;
            fromPos=claw.read();
            break;
      }

      if(fromPos<=toPos){
          for(int i=fromPos;i<=toPos;i++){
              servo2go.write(i);
              delay(servoDelay);
            }
        }else{
             for(int i=fromPos;i>=toPos;i--){
              servo2go.write(i);
              delay(servoDelay);
            }
         }
    }

void reportStatus(){
    Serial.println("*************************");
    Serial.println(" ");
    Serial.println("+Robot-Arm Status Report +");  
    Serial.print("Base Position:");Serial.println(base.read());
    Serial.print("fArm Position:");Serial.println(fArm.read());
    Serial.print("rArm Position:");Serial.println(rArm.read());
    Serial.println(" ");
    Serial.println("*************************");
  }

你可能感兴趣的:(arduino)