const int trigPin = 5;
const int echoPin = 18;
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(9800);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm = duration * SOUND_SPEED/2;
distanceInch = distanceCm * CM_TO_INCH;
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
delay(1000);
}
//+ralay
const int trigPin = 5;
const int echoPin = 18;
int relay = 15;
#define SOUND_SPEED 0.034
#define CM 1
long duration;
float distanceCm;
void setup() {
Serial.begin(9800);
pinMode(relay, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
if ( distanceCm >= 15) {
digitalWrite(relay, 0);
}
if ( distanceCm <= 10) {
digitalWrite(relay, 1);
}
duration = pulseIn(echoPin, HIGH);
distanceCm = duration * SOUND_SPEED/2;
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
delay(500);
}
// เสียง
const int trigPin = 5;
const int echoPin = 18;
int relay = 15;
int buzzerpin = 16 ;
#define SOUND_SPEED 0.034
#define CM 1
long duration;
float distanceCm;
void setup() {
Serial.begin(9800);
pinMode(relay, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerpin,OUTPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
if ( distanceCm >= 15) {
digitalWrite(relay, 0);
digitalWrite(buzzerpin,HIGH);
}
if ( distanceCm <= 10) {
digitalWrite(relay, 1);
digitalWrite(buzzerpin,LOW);
}
duration = pulseIn(echoPin, HIGH);
distanceCm = duration * SOUND_SPEED/2;
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
delay(500);
}