94 lines
1.9 KiB
Arduino
94 lines
1.9 KiB
Arduino
|
// Code for the Eye Protection Hat by Görkem Bozkurt (https://gorkem.cc)
|
||
|
// Based on the example sound level sketch from Adafruit(https://learn.adafruit.com/adafruit-microphone-amplifier-breakout/measuring-sound-levels)
|
||
|
// details here:
|
||
|
|
||
|
#include <Servo.h>
|
||
|
|
||
|
float sensitivity = 3; // a value between 0 and 3.30
|
||
|
|
||
|
Servo meservo;
|
||
|
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
|
||
|
unsigned int sample;
|
||
|
int led = 10;
|
||
|
bool isUp = true;
|
||
|
int c = 0;
|
||
|
|
||
|
void setup()
|
||
|
{
|
||
|
meservo.attach(2);
|
||
|
pinMode(led,OUTPUT);
|
||
|
Serial.begin(9600);
|
||
|
meservo.write(40);
|
||
|
delay(1000);
|
||
|
meservo.detach();
|
||
|
}
|
||
|
|
||
|
|
||
|
void loop()
|
||
|
|
||
|
{
|
||
|
unsigned long startMillis= millis(); // Start of sample window
|
||
|
unsigned int peakToPeak = 0; // peak-to-peak level
|
||
|
|
||
|
unsigned int signalMax = 0;
|
||
|
unsigned int signalMin = 1024;
|
||
|
|
||
|
// collect data for 50 mS
|
||
|
while (millis() - startMillis < sampleWindow)
|
||
|
{
|
||
|
sample = analogRead(1);
|
||
|
if (sample < 1024) // toss out spurious readings
|
||
|
{
|
||
|
if (sample > signalMax)
|
||
|
{
|
||
|
signalMax = sample; // save just the max levels
|
||
|
}
|
||
|
else if (sample < signalMin)
|
||
|
{
|
||
|
signalMin = sample; // save just the min levels
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
|
||
|
double volts = (peakToPeak * 5.0) / 1024; // convert to volts
|
||
|
|
||
|
if(volts>sensitivity){
|
||
|
if(c>10){
|
||
|
motorDown();
|
||
|
}else{
|
||
|
motorUp();
|
||
|
}
|
||
|
c+=1;
|
||
|
|
||
|
}else{
|
||
|
c=0;
|
||
|
motorUp();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void motorUp(){
|
||
|
Serial.println("Safe");
|
||
|
digitalWrite(led,LOW);
|
||
|
if(!isUp){
|
||
|
meservo.attach(2);
|
||
|
meservo.write(40);
|
||
|
isUp=true;
|
||
|
delay(500);
|
||
|
meservo.detach();
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
void motorDown(){
|
||
|
Serial.println("Drill in use");
|
||
|
digitalWrite(led,HIGH);
|
||
|
if(isUp){
|
||
|
meservo.attach(2);
|
||
|
meservo.write(170);
|
||
|
isUp=false;
|
||
|
delay(500);
|
||
|
meservo.detach();
|
||
|
}
|
||
|
|
||
|
}
|