void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
#define MOTION_SENSOR_PIN 2 // The Arduino Nano pin connected to the OUTPUT pin of motion sensor
#define LED_PIN 7 // The Arduino Nano pin connected to the LED
int motion_state = LOW; // current state of motion sensor's pin
int prev_motion_state = LOW; // previous state of motion sensor's pin
void setup() {
Serial.begin(9600); // Initialize the Serial to communicate with the Serial Monitor.
pinMode(MOTION_SENSOR_PIN, INPUT); // set arduino pin to input mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
}
void loop() {
prev_motion_state = motion_state; // store old state
motion_state = digitalRead(MOTION_SENSOR_PIN); // read new state
if (prev_motion_state == LOW && motion_state == HIGH) { // pin state change: LOW -> HIGH
Serial.println("Motion detected!");
digitalWrite(LED_PIN, HIGH); // turn on
}
else if (prev_motion_state == HIGH && motion_state == LOW) { // pin state change: HIGH -> LOW
Serial.println("Motion stopped!");
digitalWrite(LED_PIN, LOW); // turn off
}
}