// --- Pin Map ---
#define TRIG_PIN A0
#define ECHO_PIN A1
#define BTN1_PIN 12 // button 1
#define LED1_PIN 7 // LED 1
#define BTN2_PIN 13 // button 2
#define LED2_PIN 6 // LED 2
const int US_THRESHOLD_CM = 20;
const unsigned long PRINT_MS = 1000;
unsigned long lastPrint = 0;
// --- Ultrasonic distance ---
long readDistanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (duration == 0) return 9999;
return duration * 0.034 / 2;
}
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BTN1_PIN, INPUT); // use simple INPUT like your example
pinMode(BTN2_PIN, INPUT);
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
digitalWrite(LED1_PIN, LOW);
digitalWrite(LED2_PIN, LOW);
}
void loop() {
// --- Ultrasonic ---
long distance = readDistanceCm();
int actionUS = (distance <= US_THRESHOLD_CM) ? 1 : 0;
// --- Button reads ---
bool btn1Pressed = (digitalRead(BTN1_PIN) == HIGH);
bool btn2Pressed = (digitalRead(BTN2_PIN) == HIGH);
// --- LED control ---
if (btn1Pressed) {
digitalWrite(LED1_PIN, HIGH);
} else {
digitalWrite(LED1_PIN, LOW);
}
if (btn2Pressed) {
digitalWrite(LED2_PIN, HIGH);
} else {
digitalWrite(LED2_PIN, LOW);
}
// --- Action flags ---
int actionLED1 = btn1Pressed ? 1 : 0;
int actionLED2 = btn2Pressed ? 1 : 0;
// --- Print once per second ---
unsigned long now = millis();
if (now - lastPrint >= PRINT_MS) {
lastPrint = now;
Serial.print("Action one US : "); Serial.println(actionUS);
Serial.print("Action two LD1 : "); Serial.println(actionLED1);
Serial.print("Action three LD2 : "); Serial.println(actionLED2);
Serial.println("-----------------------");
}
}