[Atmel] Arduino人体接近报警之三

[复制链接]
1497|0
 楼主| ddllxxrr 发表于 2014-8-1 06:27 | 显示全部楼层 |阅读模式
本文是转自国外网站之三:编程

当前步做好之后就可做下一步了。就是编程,读者可把作者的程序,贴到Arduino IDE上然后更新运行
  1. // Uses a PIR sensor to detect movement, buzzes a buzzer
  2. // more info here: http://blog.makezine.com/projects/pir-sensor-arduino-alarm/
  3. // email me, John Park, at jp@jpixl.net
  4. // based upon:
  5. // PIR sensor tester by Limor Fried of Adafruit
  6. // tone code by michael@thegrebs.com


  7. int ledPin = 13;                // choose the pin for the LED
  8. int inputPin = 2;               // choose the input pin (for PIR sensor)
  9. int pirState = LOW;             // we start, assuming no motion detected
  10. int val = 0;                    // variable for reading the pin status
  11. int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

  12. void setup() {
  13.   pinMode(ledPin, OUTPUT);      // declare LED as output
  14.   pinMode(inputPin, INPUT);     // declare sensor as input
  15.   pinMode(pinSpeaker, OUTPUT);
  16.   Serial.begin(9600);
  17. }

  18. void loop(){
  19.   val = digitalRead(inputPin);  // read input value
  20.   if (val == HIGH) {            // check if the input is HIGH
  21.     digitalWrite(ledPin, HIGH);  // turn LED ON
  22.     playTone(300, 160);
  23.     delay(150);

  24.    
  25.     if (pirState == LOW) {
  26.       // we have just turned on
  27.       Serial.println("Motion detected!");
  28.       // We only want to print on the output change, not state
  29.       pirState = HIGH;
  30.     }
  31.   } else {
  32.       digitalWrite(ledPin, LOW); // turn LED OFF
  33.       playTone(0, 0);
  34.       delay(300);   
  35.       if (pirState == HIGH){
  36.       // we have just turned of
  37.       Serial.println("Motion ended!");
  38.       // We only want to print on the output change, not state
  39.       pirState = LOW;
  40.     }
  41.   }
  42. }
  43. // duration in mSecs, frequency in hertz
  44. void playTone(long duration, int freq) {
  45.     duration *= 1000;
  46.     int period = (1.0 / freq) * 1000000;
  47.     long elapsed_time = 0;
  48.     while (elapsed_time < duration) {
  49.         digitalWrite(pinSpeaker,HIGH);
  50.         delayMicroseconds(period / 2);
  51.         digitalWrite(pinSpeaker, LOW);
  52.         delayMicroseconds(period / 2);
  53.         elapsed_time += (period);
  54.     }
  55. }


您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:http://shop34182318.taobao.com/ http://shop562064536.taobao.com

2404

主题

7004

帖子

68

粉丝
快速回复 在线客服 返回列表 返回顶部