arduino-舵机

arduino-舵机

  • 1. 认识舵机
  • 2. 舵机转动(利用for循环)
  • 3. 电位器控制舵机
  • 4. 例子4:电位器控制舵机(利用映射实现)

1. 认识舵机

#include 
Servo x;
void setup() {
  // put your setup code here, to run once:
  x.attach(7);
}

void loop() {
  // put your main code here, to run repeatedly:
  x.write(0);     //给舵机写入角度
  delay(500);     //等待转动
  x.write(50);
  delay(500);
  x.write(100);
  delay(500);
  x.write(180);
  delay(500);     
}

2. 舵机转动(利用for循环)

#include 
Servo x;
void setup() {
  // put your setup code here, to run once:
  x.attach(7);
}

void loop() {
  // put your main code here, to run repeatedly:
  for (int i = 0; i <= 180; i++) {
    x.write(i);
    delay(10);
  }
  for (int i = 180; i <= 0; i--) {
    x.write(i);
    delay(10);
  }
}

3. 电位器控制舵机

注意:

  1. 电位器:中间模拟端口,两边正负极
  2. 舵机:棕色代表负极,红色代表正极,黄色代表端口
#include 
Servo x;
int a;
void setup() {
 Serial.begin(9600);
 x.attach(7); //相当于pinMode,舵机连接的端口
 pinMode(A1,INPUT);
}

void loop() {
 a = analogRead(A1);
 x.write(a/5);
 Serial.println(a/5);
}

4. 例子4:电位器控制舵机(利用映射实现)

#include
Servo myServo;

void setup() {
  myServo.attach(7);
}
void loop() {
  int val = analogRead(A0);
  val = map(val, 0, 1023, 0, 180);
  myServo.write(val);
  delay(100);
}

你可能感兴趣的:(arduino,arduino)