const int trig = 8; // 触发信号
const int echo = 5; // 反馈信号
#include
Servo myservo0;
float pos0 = 0;
float i= 45;
float S=100;
void setup()
{
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
//触发端口设置为输出,反馈端口设置为输入
Serial.begin(9600);
myservo0.attach(9);
myservo1.attach(10);
myservo2.attach(11);
myservo3.attach(6);// attaches the servo on pin 9 to the servo object
}
void loop()
{
long IntervalTime=0; //定义一个时间变量
for(pos0 = i; pos0 < 48; pos0 += 0.5) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo0.write(pos0); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
i=pos0;
for(pos1 = k; pos1 <73; pos1+= 0.5) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo1.write(pos1); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
k=pos1;
while(S>15){
S=0;
digitalWrite(trig, 1);//置高电平
delayMicroseconds(15);//延时 15us
digitalWrite(trig, 0);//设为低电平
IntervalTime=pulseIn(echo, HIGH);//用自带的函数采样反馈的高电平的宽度, 单位 us
float S=IntervalTime/58.00; //使用浮点计算出距离,单位 cm
Serial.println(S);//通过串口输出距离数值
IntervalTime=0;//对应的数值清零。
delay(500);//延时间隔决定采样的频率,根据实际需要变换参数
}