Introduction: ARDUINO MOTION SENSOR
For this simple project all you need is
the arduino and software
pir motion sensor
speaker or buzzer
Step 1: Connect Your Speaker and Sensor
first connect the sensor middle pin to digital pin 2 and the GND to the GND on the arduino and lastly the power pin goes to the 5V on the arduino.
second the step is the speaker that is pluged into the didgital pin 10, 11 or 12 and the black wire goes to the GND on the arduino.
Step 2: Coding
the code for this project is
int ledPin = 13;
int inputPin = 2; int pirState = LOW; int val = 0; int pinSpeaker = 10;
void setup() { pinMode(ledPin, OUTPUT); pinMode(inputPin, INPUT); pinMode(pinSpeaker, OUTPUT); Serial.begin(9600); }
void loop(){ val = digitalRead(inputPin); if (val == HIGH) { digitalWrite(ledPin, HIGH); playTone(300, 160); delay(150);
if (pirState == LOW) { Serial.println("Motion detected!"); pirState = HIGH; } } else { digitalWrite(ledPin, LOW); playTone(0, 0); delay(300); if (pirState == HIGH){ Serial.println("Motion ended!"); pirState = LOW; } } }
void playTone(long duration, int freq) { duration *= 1000; int period = (1.0 / freq) * 1000000; long elapsed_time = 0; while (elapsed_time < duration) { digitalWrite(pinSpeaker,HIGH); delayMicroseconds(period / 2); digitalWrite(pinSpeaker, LOW); delayMicroseconds(period / 2); elapsed_time += (period); } }
to download the coding software go to https://www.arduino.cc/en/Main/Software
Comments
Question 5 years ago on Step 2
Can you get the speaker to play anything, like any MP3 file?
And what sensor and speaker do you use?