วันอังคารที่ 5 กันยายน พ.ศ. 2560

Robot Car Part 2 Swing sensor for scan area





HC-SR04  to Arduino Nano

Vcc  >>  5 VccTrig  >>  D13Echo >>  D12Gnd  >>  Gnd

Servo wiring to Arduino Nano


Red      >> 5Vcc

Brown  >> GND

Orange >> pin 9 



Code

#include <Servo.h>
Servo myservo;
const int pingPin = 13;
int inPin = 12;


void setup() {
myservo.attach(9);
Serial.begin(9600);
}

void loop()
{


long duration, cm;

pinMode(pingPin, OUTPUT);


digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);

cm = microsecondsToCentimeters(duration);

 if (cm < 10) {  
    //  servo

        myservo.write(0); 
        delay(1000);      
        myservo.write(90); 
        delay(1000);      
        myservo.write(270); 
        delay(1000);    
  // end servo
}
  else {
    myservo.write(90);
  }
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);


}

long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}





ไม่มีความคิดเห็น:

แสดงความคิดเห็น