Skip to content

Instantly share code, notes, and snippets.

@harrisonhjones
Last active August 29, 2015 14:07
Show Gist options
  • Save harrisonhjones/403398d12fe8f018bbad to your computer and use it in GitHub Desktop.
Save harrisonhjones/403398d12fe8f018bbad to your computer and use it in GitHub Desktop.
Halloween Prop Sparkcore Code
int RELAY1 = D0;
int RELAY2 = D1;
int RELAY3 = D2;
int MOTION1 = D3;
unsigned long lastMotionTime = 0;
int propDelay = 10000; // In milliseconds(10 seconds)
int propOnTime = 20000; // In milliseconds(20 seconds)
int state = 0; // Normal operation = 0, Waiting to actuate prop in 10 seconds = 1, Actuaing props for 20 seconds = 2
void setup()
{
// Initilize the pins
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);
pinMode(RELAY3, OUTPUT);
pinMode(MOTION1, INPUT);
// Initialize all relays to an OFF state
digitalWrite(RELAY1, LOW);
digitalWrite(RELAY2, LOW);
digitalWrite(RELAY3, LOW);
// Register two functions, one to allow for individual actuation of each relay and the other to test the effect
Spark.function("relay", relayControl);
Spark.function("test", test);
}
void loop()
{
// In the normal "reset" state wait for a LOW signal on the motion detector. When that motion is seen record the time and go to the next state
if(state == 0)
{
if(digitalRead(MOTION1) == LOW)
{
lastMotionTime = millis();
state = 1;
}
else
{
// In the normal state the relays should not be ON"
digitalWrite(RELAY1, LOW);
digitalWrite(RELAY2, LOW);
digitalWrite(RELAY3, LOW);
}
}
// Wait for 10 seconds then go to the next state
else if(state == 1)
{
if((lastMotionTime + propDelay) < millis())
{
state = 2;
}
}
// For the next 20 seconds bring the relays "ON". Once 20 seconds has passed go back to the normal or "rest" state
else if(state == 2)
{
if((lastMotionTime + propOnTime) < millis())
{
state = 0;
}
else
{
digitalWrite(RELAY1, HIGH);
digitalWrite(RELAY2, HIGH);
digitalWrite(RELAY3, HIGH);
}
}
// Catch any mistakes and just go back to the normal state
else
{
state = 0;
}
}
int test(String command)
{
// To test just simulate a low signal on the motion
lastMotionTime = millis();
state = 1;
}
// Taken from the relay example code in the SparkCore docs
// command format r1,HIGH
int relayControl(String command)
{
int relayState = 0;
// parse the relay number
int relayNumber = command.charAt(1) - '0';
// do a sanity check
if (relayNumber < 1 || relayNumber > 3) return -1;
// find out the state of the relay
if (command.substring(3,7) == "HIGH") relayState = 1;
else if (command.substring(3,6) == "LOW") relayState = 0;
else return -1;
// write to the appropriate relay
digitalWrite(relayNumber-1, relayState);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment