天天看點

day-1 舵機超音波測距離-arduino

#include<Servo.h>
const int sPin = ;
const int rPin = ;
int pos;
float distance;
Servo myduo;
void setup(){
        myduo.attach();
        Serial.begin();
        pinMode(sPin, OUTPUT);
        pinMode(rPin, INPUT);
}
void loop()
{
      for(pos=;pos<=;pos+=){
        myduo.write(pos);
        digitalWrite(sPin, LOW);
        delayMicroseconds();
        digitalWrite(sPin, HIGH);
        delayMicroseconds();
        digitalWrite(sPin, LOW);
        distance = pulseIn(rPin, HIGH) / ;
        Serial.print(distance);
        Serial.print("cm");
        Serial.println();
        delay();
}
 for(pos=;pos>=;pos-=){
        myduo.write(pos);
        digitalWrite(sPin, LOW);
        delayMicroseconds();
        digitalWrite(sPin, HIGH);
        delayMicroseconds();
        digitalWrite(sPin, LOW);
        distance = pulseIn(rPin, HIGH) / ;
        Serial.print(distance);
        Serial.print("cm");
        Serial.println();
        delay();
}
}
           

繼續閱讀