#define BUTTON_PIN 2
#define BUZZER_PIN 8
const int pingPin = 13;
int inPin = 12;
int RGBPin[] = { 11, 10, 9 };
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP); // ใช้ pull-up ภายใน
pinMode(BUZZER_PIN, OUTPUT);
pinMode(pingPin, OUTPUT);
pinMode(RGBPin[0], OUTPUT);
pinMode(RGBPin[1], OUTPUT);
pinMode(RGBPin[2], OUTPUT);
}
void SetRGB(int r, int g, int b) {
analogWrite(RGBPin[0], r);
analogWrite(RGBPin[1], g);
analogWrite(RGBPin[2], b);
}
void loop(){
long duration, cm;
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);
cm = microsecondsToCentimeters(duration);
if (digitalRead(BUTTON_PIN) == HIGH) {
SetRGB(255, 0, 0); // ปุ่มกดอยู่ เปิดไฟแดง
cm = 400;
}
if(cm<400){
digitalWrite(BUZZER_PIN, HIGH); // เปิดเสียง
SetRGB(255, 0, 0); // Red
}else{
digitalWrite(BUZZER_PIN, LOW); // ปิดเสียง
SetRGB(0, 255, 0); // Green
}
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;
}