const int TRIG_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 9; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int LED_PIN = 3; // Arduino pin connected to LED's pin
const int BUTTON_PIN = 11;
const int DISTANCE_THRESHOLD = 50; // centimeters
int lastButtonState = 0; // the previous state of button 0 = low
int currentButtonState = 0; // the current state of button 0 = low
int ledBrightness;
int sensorVal;
// variables will change:
float duration_us, distance_cm;
void setup() {
Serial.begin (9600); // initialize serial port
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
pinMode(BUTTON_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// generate 10-microsecond pulse to TRIG pin
//lastButtonState = currentButtonState;
currentButtonState = digitalRead(BUTTON_PIN);
if (currentButtonState = lastButtonState) {
if (currentButtonState == HIGH) {
Serial.println("button is pressed");
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;
//Light brightness and stuff
/*sensorVal = analogRead(distance_cm);
ledBrightness = map(sensorVal, 0, 1186, 0, 255);
analogWrite(LED_PIN, ledBrightness);*/
if(distance_cm < DISTANCE_THRESHOLD)
digitalWrite(LED_PIN, HIGH); // turn on LED
else
digitalWrite(LED_PIN, LOW); // turn off LED
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
} else {
Serial.println("button is released");
}
}
delay(500);
lastButtonState = currentButtonState;
}
// delay(500);
//button first test
//lastButtonState = currentButtonState;
//currentButtonState = digitalRead(BUTTON_PIN);
//erial.println(lastButtonState);
//Serial.println(currentButtonState);
// if(lastButtonState == HIGH && currentButtonState == LOW){
// }
// //
//}