一个arduino控制舵机的demo
模块:舵机 超声波 蓝牙
功能:当物体距离小于10cm时控制夹子夹住物体,并向外传输实测的距离。
程序:
#include <Servo.h>
int TrgPin = A0;
int EcoPin = A1;
int dist;
Servo myservo; // 定义Servo对象来控制
int pos = 0; // 角度存储变量
void setup() {
Serial.begin(9600);
myservo.attach(9);// 控制线连接数字9
pinMode(TrgPin, OUTPUT);
// 设置EcoPin为输入状态
pinMode(EcoPin, INPUT);
}
void loop() {
digitalWrite(TrgPin, LOW);
delayMicroseconds(8);
digitalWrite(TrgPin, HIGH);
// 维持10毫秒高电平用来产生一个脉冲
delayMicroseconds(10);
digitalWrite(TrgPin, LOW);
// 读取脉冲的宽度并换算成距离
dist = pulseIn(EcoPin, HIGH) / 58.00;
Serial.println(dist);
if(dist<10){
for (pos ; pos > 0; pos --) { // 从180°到0°
myservo.write(pos); // 舵机角度写入
delay(5); // 等待转动到指定角度
}
}
if(dis