const int pingpin = 5;
int inpin = 18;
#define LED 17
void setup() {
Serial.begin(9600);
pinMode(pingpin, OUTPUT); // ขา itrg
pinMode(inpin, INPUT); // ขา Echo
pinMode(LED, OUTPUT);
}
void loop() {
long duration, cm; //เก็บข้อมูลจำนวณเต็มแบบคิดเครื่องหมาย
/////////////////////////ภาคส่งสัญญาน////////////////
digitalWrite(pingpin, LOW);
delayMicroseconds(2);
digitalWrite(pingpin, HIGH);
delayMicroseconds(5);
digitalWrite(pingpin, LOW);
////////////////////////////ภาครับสัญญาน//////////////////////////////////
duration = pulseIn(inpin,HIGH);
cm = microsecondsToCentimeters(duration); // ต้องมี libery
////////////////////////////ภาคแสดงผล//////////////////////
Serial.println();
delay(100);
////////////////ภาคควบคุม///////////////////
if(cm > 100){
digitalWrite(LED, HIGH);
Serial.print("Distance is Near");
}
else{
digitalWrite(LED, LOW);
Serial.print("Distance is Far");
}
}
///////////////Loop สร้างเพื่อแปลงเป็นเซ็นติเมตร///////////////////////
long microsecondsToCentimeters(long microseconds){
return microseconds/29/2;
}