1 接线图基础舵机控制程序
![4413f0227e631331e3d702855a217f54.png](https://i-blog.csdnimg.cn/blog_migrate/e2f41a97699d174e3c2a0335e84c7b13.jpeg)
代码:
图形化:如果有串口输入,转动对应的角度
![3cd21d1550c941e83f686f89502660d8.png](https://i-blog.csdnimg.cn/blog_migrate/bdb6011e68230a47a5cab6c1beb86a05.jpeg)
等待输入,转动一定角度2
#include <Servo.h>
int servoPin=6; //定义舵机引脚
int pos = 0; //定义角度值
int servoDelay=50; //定义时间
Servo my_servo; //定义舵机对象
void setup(){
Serial.begin(9600); //打开串口
my_servo.attach(servoPin); //绑定串口引脚
}
void loop(){
Serial.println("please intput an angle:");
while (Serial.available() ==0){} //等待串口输入数据
pos = Serial.parseInt; //将串口数据转换为整型读取到pos
my_servo.write(pos); //转一定角度
delay(servoDelay); //延迟
}
代码2 让舵机 从0-180 再从180-0
#include <Servo.h>
int pos = 0; // variable to store the servo position
int servoPin= 9;
int servoDelay=25;
Servo myPointer;
void setup()
{
Serial.begin(9600);
myPointer.attach(servoPin); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos=15; pos<=170; pos=pos+1) {
myPointer.write(pos);
delay(servoDelay);
}
for (pos=170; pos>=15; pos=pos-1) {
myPointer.write(pos);
delay(servoDelay);
}
}
2 .电位器 控制
![ab0aa3311b4fb1d9a6357c712dae5838.png](https://i-blog.csdnimg.cn/blog_migrate/065b78b4113a296a6512f455f52dd787.jpeg)
![5747453f92138b5e699967f4663739b3.png](https://i-blog.csdnimg.cn/blog_migrate/99f245bda4f43cd0c964b4cac7ca719c.jpeg)
#include <Servo.h>
int pos = 0;
int serPin = 6;
int delayTime = 50;
Servo my_servo;
void setup(){
Serial.begin(9600);
my_servo.attach(serPin);
}
void loop(){
pos = analogRead(A0);
pos = map(pos,0,1023,0,180);
my_servo.write(pos);
delay(delayTime);
}
3 线路3超声波传感器控制舵机模块
![da41f726c5b706dcf609026ac0a35eff.png](https://i-blog.csdnimg.cn/blog_migrate/c0748ffca9f6aa80dc6b15b94a951ae2.jpeg)
![ec902b3ffcb04f1170ede266f3c96ff8.png](https://i-blog.csdnimg.cn/blog_migrate/e145f12afc765bd1eab9463167071b11.jpeg)