#include <Adafruit_NeoPixel.h>
#include <Servo.h>
//pin to control relay
#define relayPin 4
// PIR connection pin
#define pirPin 2
bool pirState;
//Buzzer onnection pin
#define buzzerPin 9
bool buzzerState;
// Neopixel connection pin and number of pixels
#define neoPixel 3
#define NUMPIXELS 16
// Servo connections pins
#define servoPin 5 //Servo to turn turret
#define servoDartPin 6 //Servo to load dart in fly launcher
bool alarmState = HIGH;
byte alarmCounter = 0;
//Timing variables
unsigned long currentMillis;
unsigned long servoStartMillis = 0;
unsigned long dartLoaderStartMillis = 0;
const byte alarmDelay = 250;
const byte loaderDelay = 500;
unsigned long alarmStartMillis = 0;
const unsigned StepPeriod = 50;
const int StepIncrement = 2;
// Create Servo objects
Servo servo; //Turret rotation
Servo servoDart; //Dart loading
// Create NeoPixel object
Adafruit_NeoPixel pixels(NUMPIXELS, neoPixel, NEO_GRB + NEO_KHZ800);
void SERVO_sweep(){
static int pos = 0;
static int increment = StepIncrement;
if (currentMillis - servoStartMillis >= StepPeriod)
{
servoStartMillis = currentMillis;
pos += increment;
if (pos > 180)
{
pos = 180;
increment = -StepIncrement;
}
if (pos < 0)
{
pos = 0;
increment = StepIncrement;
}
servo.write(pos);
}
}
void alarm(bool state){
if(currentMillis - alarmStartMillis >= alarmDelay && alarmCounter < 10){
if(state == HIGH){
tone(buzzerPin, 300);
for(int i=0; i<NUMPIXELS; i++) { // For each pixel...
pixels.setPixelColor(i, pixels.Color(200, 0, 0));
}
pixels.show(); // Send the updated pixel colors to the hardware.
} else {
pixels.clear(); // Set all pixel colors to 'off'
pixels.show();
noTone(buzzerPin);
}
alarmState = !alarmState;
alarmCounter += 1;
alarmStartMillis = currentMillis;
}
alarmCounter = 0;
}
void dartLoader(){
if(currentMillis - dartLoaderStartMillis >= loaderDelay){
servoDart.write(90);
} else {
servoDart.write(180);
}
dartLoaderStartMillis = currentMillis;
}
void setup(){
Serial.begin(9600);
pinMode(pirPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(relayPin, OUTPUT);
pixels.begin();
servo.attach(servoPin); //Activate servo
servoDart.attach(servoDartPin); //Activate dart pushing servo
}
void loop(){
currentMillis = millis();
pirState = digitalRead(pirPin);
SERVO_sweep();
dartLoader();
/*
if(pirState == HIGH){
digitalWrite(relayPin, HIGH);
alarm(alarmState); //pass the nuber of times the alarm should flash
} else {
digitalWrite(relayPin, LOW);
}
*/
}