【Arduino实战教程 002】控制舵机转动

实验环境:
Arduino1.8.3 IDE
Arduino mega 2560
奥松移动机器人舵机版本
在做机器人移动控制时,难免会在选择电机和舵机之间有些困惑。简单讲,电机和舵机是两种不同的驱动方式,用的控制器不同,电机是靠电机驱动板驱动,舵机一般是用能驱动舵机的控制器,或者是其他驱动舵机的板子来驱动,还有就是电机只能正转和反转,舵机是可以控制旋转角度。舵机其实也是一种电机,它是使用一个反馈系统来控制电机的位置。舵机通常情况下只能旋转180°。硬件的连接不详细讲解,此处直接上代码:

/**************************************************************
 作者:DaveBobo
 博客:http://blog.csdn.net/DaveBobo/article/details/78755152
**************************************************************/
#include  //载入 Servo.h 库文件
Servo coreservo5; //建立一个舵机对象,名称为 coreservo5
Servo coreservo9; 

int pos = 0;    // variable to store the servo position

void setup() {
  coreservo5.attach(5);//将引脚 5 上的舵机与舵机对象连接起来
  coreservo9.attach(9);
}

void loop() {
  check5();
  check9();
  /* If you wanted to read the angle of your servo at any given time, use servoname.read();
   * If you wanted to write a pulse of a certain width use servoname.writemicroseconds(value in microseconds);
   */
}

void check5()
{
 for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    coreservo5.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
  {                                
    coreservo5.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
}

void check9()
{
 for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    coreservo9.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
  {                                7
    coreservo9.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
}

代码编写好,编译上传即可。上传成功后我们可以观察到两个舵机已经开始转动了。
Reference:
https://jingyan.baidu.com/article/cd4c297903fb17756e6e6008.html?qq-pf-to=pcqq.c2c
http://www.arduino.cn/thread-12589-1-1.html
https://www.w3cschool.cn/arduino/arduino_servo_motor.ht

你可能感兴趣的:(Arduino和树莓派)