主页 > 硬件 > DIY声控延时小夜灯

DIY声控延时小夜灯

2016年5月11日 DIY声控延时小夜灯无评论 阅读: 13,741 次

小孩怕黑,动手做了一个声控小夜灯

 

实现功能:

拍一次掌,灯亮,延时15分钟(900秒)后自动关闭,如果想提前关闭,则拍两次掌即可。

 

一、所需材料:

1、单片机:Arduino,我用的是Arduino uno

2、声音检测模块:

3、继电器模块

4、USB灯泡

 

二、连线

声音检测模块的输出接arduino的D2引脚,用于中断0触发

继电器的控制输入接arduino的D11引脚,用于控制继电器通断

继电器模块做了点改造,加了一个USB母头,可以直接控制USB灯泡的通断电:

声音检测模块电源(3.3V)和继电器模块的电源(5V)都取至arduino。

三、程序

/*
 声控延时开关
 */
int ledPin = 13;       // arduino调试灯
int pbIn = 0;                  // 定义中断引脚为0,也就是D2引脚;
int outPin=11;                //控制继电器引脚
volatile int count = 0;      // 定义中断触发变量
 
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
 
  pinMode(ledPin, OUTPUT);
  pinMode(outPin, OUTPUT);  
  digitalWrite(outPin, LOW);    // turn the LED off by making the voltage LOW
  count=0;
  //引脚2下降沿触发中断
   attachInterrupt(pbIn, stateChange, FALLING);
}
 
// the loop routine runs over and over again forever:
void loop() {
 
 Serial.println(count);//调试
 delay(1);        // delay in between reads for stability
 if(count>0) 
 {
   //开灯
   digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
   digitalWrite(outPin, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);//等待读数稳定
   int last=count;
   int ncount=0;
 
   for(int i=0;i<1800;i++)//缺省延时900秒
   {
 
    if(count>last)
    {
     ncount++;
     last=count;
    }
    if((i%6)==0)
    {
      count=0;
      ncount=0;
      last=0;
    }
    //3秒内连敲2下关灯
    if(ncount>=2)
    break;
    delay(500);//延时等待读数稳定
   }
 
 
   digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
   digitalWrite(outPin, LOW);    // turn the LED off by making the voltage LOW
   //等3秒,防止误触发
   delay(3000);
   count=0;
  }
}
void stateChange()
{
  //检测到声音后count加一,一次声音可以触发多次中断
  count++;
}

声音检测设置为中断触发,需要注意的是,比如拍一次掌声,可能会有多次触发信号,因此在程序中加入了500ms的稳定时间,程序不是通过count(中断触发数)来判断掌声数,而是通过ncount变量(阶段的读数变化次数)来判断。

 

可结合小米插座使用,设置每天晚上21:00至白天7:00给上面的模块供电,其他时间断电。

 

发表评论

新用户的评论需审核后才会显示;

电子邮件地址不会被公开;
必填项已用*标注