day-1 舵机超声波测距离-arduino

#include
const int sPin = 13;
const int rPin = 12;
int pos;
float distance;
Servo myduo;
void setup(){
        myduo.attach(3);
        Serial.begin(9600);
        pinMode(sPin, OUTPUT);
        pinMode(rPin, INPUT);
}
void loop()
{
      for(pos=0;pos<=180;pos+=4){
        myduo.write(pos);
        digitalWrite(sPin, LOW);
        delayMicroseconds(2);
        digitalWrite(sPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(sPin, LOW);
        distance = pulseIn(rPin, HIGH) / 58.00;
        Serial.print(distance);
        Serial.print("cm");
        Serial.println();
        delay(1000);
}
 for(pos=180;pos>=0;pos-=4){
        myduo.write(pos);
        digitalWrite(sPin, LOW);
        delayMicroseconds(2);
        digitalWrite(sPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(sPin, LOW);
        distance = pulseIn(rPin, HIGH) / 58.00;
        Serial.print(distance);
        Serial.print("cm");
        Serial.println();
        delay(1000);
}
}

你可能感兴趣的:(arduino折腾日记)