#include <Servo.h>
Servo myservo;
int TrgPin = A0; // 设置超声波发送引脚
int EcoPin = A1; // 设置超声波接收引脚
int PWM = 3; // 设置舵机引脚
float dist;
void setup() {
myservo.attach(PWM); //绑定舵机的引脚号
Serial.begin(9600); // 设置串口波特率
pinMode(TrgPin, OUTPUT); // 设置引脚为输出模式
pinMode(EcoPin, INPUT); // 设置引脚为接收模式
}
void loop() {
digitalWrite(TrgPin, LOW); // 向超声波引脚输出低位电压0
delayMicroseconds(8); // 等待8毫秒
digitalWrite(TrgPin, HIGH); //向超声波引脚输出高位电压1
delayMicroseconds(10); // 等待10毫秒
digitalWrite(TrgPin, LOW); //向超声波引脚输出低位电压0
dist = pulseIn(EcoPin, HIGH) /58; // 读取接收超声波数据,并且将模拟信号换算成cm
Serial.print("Distance:"); // 向串口发送数据
Serial.print(dist); // 向串口发送数据
Serial.println("cm"); // 向串口发送数据
delay(300); // 等待 800毫秒
if (dist <10){ // 判断距离是否小过10CM
myservo.write(90); // 控制舵机旋转
delay(20); // 等待 20毫秒
}
else
{
myservo.write(0); // 控制舵机旋转
}
}
问如何在不增加超声波的情况下多控制一个舵机;
实在不行也可以考虑增加一个超声波,但芯片只能是一块。