#include <IRremote.hpp>
#include <Servo.h>
#define IR_BUTTON_1 224 //12
#define IR_BUTTON_2 168 //8
#define IR_BUTTON_3 144 //66
const int BUZZ_PIN = 7; // buzzer pin
const int ECHO_PIN = 10; // pin for the echo
const int IR_RX_PIN = 12; // IR Reciever pin
const int SERVO_PIN = 6; // servo pin
const int TRIG_PIN = 11; // pin for the trigger
Servo bigServ; // servo object
float getRange(bool scale = false) {
float dist = 0.0;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long pulseTime = pulseIn(ECHO_PIN, HIGH);
if (scale) {
dist = (0.0136 * pulseTime) / 2; // inches
} else {
dist = (0.0343 * pulseTime) / 2; // cm
}
return dist;
}
void Noise(float distance, int freq) {
if (getRange() > 200.0) {
Serial.print("Distance: \t");
Serial.println(distance);
Serial.print("Freq: \t");
Serial.println(freq);
IrReceiver.stop();
tone(BUZZ_PIN, freq - (freq / 2));
delay(200);
tone(BUZZ_PIN, freq);
delay(200);
IrReceiver.start(); // to compensate for 8 ms stop of receiver. This enables a correct gap measurement.
//tone(BUZZ_PIN, freq - (freq / 2));
//delay(200);
//tone(BUZZ_PIN, freq);
//delay(200);
//noTone(BUZZ_PIN);
}
}
void setup() {
Serial.begin(115200);
IrReceiver.begin(IR_RX_PIN); // starts IR Reciever
pinMode(BUZZ_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
bigServ.attach(SERVO_PIN); // attaches servo object to the pin
}
void loop() {
static int pitchMap = 5;
static bool isLockOpen = false; //boolean that determines if lock closed or not
// IR receiver section -----------------------------
if (IrReceiver.decode()) { // decodes signal received
int command = IrReceiver.decodedIRData.command;
Serial.print("Command: \t");
Serial.println(command);
switch (command) {
case IR_BUTTON_1: { //if you press button one
bigServ.write(isLockOpen ? 180 : 0);
isLockOpen = !isLockOpen;
break;
}
case IR_BUTTON_2: { // adds pitch
pitchMap++;
if (pitchMap >= 10) pitchMap = 0;
//Serial.println(pitchMap);
break;
}
case IR_BUTTON_3: { // decreases pitch
pitchMap--;
if (pitchMap < 0) pitchMap = 9;
//Serial.println(pitchMap);
break;
}
}
IrReceiver.resume();
}
int freq = map(pitchMap, 0, 10, 1000, 2000);
//Serial.print("Freq: \t");
//Serial.println(freq);
float distance = getRange(); // true = inches
//Serial.print("Distance: \t");
//Serial.println(distance);
Noise(distance, freq);
}