Last active
December 17, 2015 05:08
-
-
Save aguegu/5555194 to your computer and use it in GitHub Desktop.
led switch based on brightness sensor and mic.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Wire.h> | |
#include <math.h> | |
int BH1750address = 0x23; | |
byte buff[2]; | |
int mic_pin = 2; | |
int switch_pin = 13; | |
bool is_on = false; | |
void setup() | |
{ | |
Wire.begin(); | |
Serial.begin(9600); | |
BH1750_Init(BH1750address); | |
delay(200); | |
pinMode(mic_pin, INPUT); | |
pinMode(switch_pin, OUTPUT); | |
digitalWrite(switch_pin, LOW); | |
} | |
void loop() | |
{ | |
static byte i = 0; | |
int sound = analogRead(mic_pin); | |
// sound level 100 | |
sound > 100 ? i++ : i = 0; | |
// sound big enough to last 4 measurement run | |
if (i > 4) { | |
uint16_t brightness = 0; | |
if (BH1750_Read(BH1750address) == 2) | |
{ | |
brightness=((buff[0]<<8)|buff[1])/1.2; | |
Serial.println(brightness,DEC); | |
// brightness level 200 | |
if (brightness < 200 && !is_on) { | |
digitalWrite(switch_pin, HIGH); | |
is_on = true; | |
} | |
} | |
i = 0; | |
} | |
delay(50); | |
} | |
int BH1750_Read(int address) | |
{ | |
int i=0; | |
Wire.beginTransmission(address); | |
Wire.requestFrom(address, 2); | |
while(Wire.available()) | |
{ | |
buff[i] = Wire.read(); // receive one byte | |
i++; | |
} | |
Wire.endTransmission(); | |
return i; | |
} | |
void BH1750_Init(int address) | |
{ | |
Wire.beginTransmission(address); | |
Wire.write(0x10);//1lx reolution 120ms | |
Wire.endTransmission(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment