arduino之arduino uno与舵机的使用

今天没事干就把之前玩过的Uno拿出来玩玩,今天做的就是Uno上接舵机。现在教程真多,我自己写一个以防自己忘记,也算是一个总结吧!

       

首先了解Servo类:

          servo类下有以下成员函数
          attach();                               //连接舵机,设定舵机的接口。2~13接口可利用。
          write();                                 //角度控制,用于设定舵机旋转角度的语句,可设定的角度范围是0°到180°。这条语句是直接写角度,舵机的每个转动到了一个位置都有相应的角度。舵机通过控制PWM的宽度来决定转的角度。
          writeMicroseconds();       //用于设定舵机旋转角度的语句,直接用微秒作为参数。
          read();                                 //读上一次舵机转动角度,用于读取舵机角度的语句,可理解为读取最后一条write()命令中的值。
          attached();                         //判断舵机参数是否已发送到舵机所在接口。
          detach();                            //断开舵机连接

接着看一些原理之后连线:舵机GND(棕色线,这个连到GND)、VCC(红色线,这个连5v)、Signal(橙色线,接2~13)

arduino之arduino uno与舵机的使用_第1张图片

        然后烧代码, 程序可以在IDE>File>Examples>Servo>Sweep中找到。这个代码是舵机转180度的。

#include 
Servo myservo;  //创建一个舵机控制对象
                          // 使用Servo类最多可以控制8个舵机
int pos = 0;    // 该变量用与存储舵机角度位置
/*~~~~~~~~~~~~~~~~~~~~~~~~~~华丽的分割线~~~~~~~~~~~~~~~~~~~~~~~~~~ */
void setup()
{
  myservo.attach(9);  // 该舵机由arduino第九脚控制
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~华丽的分割线 ~~~~~~~~~~~~~~~~~~~~~~~~~~ */
void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // 从0度到180度运动
  {                                                     // 每次步进一度
    myservo.write(pos);        // 指定舵机转向的角度
    delay(15);                       // 等待15ms让舵机到达指定位置
  }
  for(pos = 180; pos>=1; pos-=1)   //从180度到0度运动  
  {                                
    myservo.write(pos);         // 指定舵机转向的角度
    delay(15);                        // 等待15ms让舵机到达指定位置
  }
}

       如果你要加舵机,都是一样的,可以把signal放在2~13的任何一个,所以最多可以有12个舵机。代码如下:

/* Sweep
 by BARRAGAN  
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://arduino.cc/en/Tutorial/Sweep
*/ 

#include  
 
Servo myservo1;  // create servo object to control a servo 
                // twelve servo objects can be created on most boards
Servo myservo2;

int pos1 = 0;    // variable to store the servo position 
int pos2 = 0;

void setup() 
{ 
  myservo1.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo2.attach(10); 
} 
 
void loop() 
{ 
  for(pos1 = 0; pos1 <= 180; pos1 += 1) // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    myservo1.write(pos1);              // tell servo to go to position in variable 'pos'
    myservo2.write(pos1); 
    delay(10);                       // waits 15ms for the servo to reach the position 
  } 
  for(pos1 = 180; pos1>=0; pos1-=1)     // goes from 180 degrees to 0 degrees 
  {                                
    myservo1.write(pos1);              // tell servo to go to position in variable 'pos' 
    myservo2.write(pos1);
    delay(10);                       // waits 15ms for the servo to reach the position 
  } 
} 

附:

arduino驱动舵机,不调用库函数:http://www.arduino.cn/thread-45-1-1.html

你可能感兴趣的:(Python,&&,SCM)