NGUYỄN VĂN SUM

Wednesday, November 15, 2017

Using a PIR with Arduino

Reading PIR Sensors

Connecting PIR sensors to a microcontroller is really simple. The PIR acts as a digital output so all you need to do is listen for the pin to flip high (detected) or low (not detected).
Its likely that you'll want reriggering, so be sure to put the jumper in the H position!
Power the PIR with 5V and connect ground to ground. Then connect the output to a digital pin. In this example we'll use pin 2.
proximity_pirardbb.gif
The code is very simple, and is basically just keeps track of whether the input to pin 2 is high or low. It also tracks the state of the pin, so that it prints out a message when motion has started and stopped.
Code
  1. /*
  2. * PIR sensor tester
  3. */
  4. int ledPin = 13; // choose the pin for the LED
  5. int inputPin = 2; // choose the input pin (for PIR sensor)
  6. int pirState = LOW; // we start, assuming no motion detected
  7. int val = 0; // variable for reading the pin status
  8. void setup() {
  9. pinMode(ledPin, OUTPUT); // declare LED as output
  10. pinMode(inputPin, INPUT); // declare sensor as input
  11. Serial.begin(9600);
  12. }
  13. void loop(){
  14. val = digitalRead(inputPin); // read input value
  15. if (val == HIGH) { // check if the input is HIGH
  16. digitalWrite(ledPin, HIGH); // turn LED ON
  17. if (pirState == LOW) {
  18. // we have just turned on
  19. Serial.println("Motion detected!");
  20. // We only want to print on the output change, not state
  21. pirState = HIGH;
  22. }
  23. } else {
  24. digitalWrite(ledPin, LOW); // turn LED OFF
  25. if (pirState == HIGH){
  26. // we have just turned of
  27. Serial.println("Motion ended!");
  28. // We only want to print on the output change, not state
  29. pirState = LOW;
  30. }
  31. }
  32. }


No comments:

Post a Comment