Skip to content

Instantly share code, notes, and snippets.

@dyadica
Created March 7, 2017 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyadica/45cce156e8d1a1eade1e736d57e72524 to your computer and use it in GitHub Desktop.
Save dyadica/45cce156e8d1a1eade1e736d57e72524 to your computer and use it in GitHub Desktop.
int led1 = D3;
void setup()
{
// Set both LED pins as outputs
pinMode(led1, OUTPUT);
// Set both LED's to off by writing
// LOW to the pin.
digitalWrite(led1, LOW);
// Register the subscription and assign
// a handler for it
Particle.subscribe("ledToggle", myHandler);
}
// The handler for the subscription
void myHandler(String event, String data)
{
if(data == "on")
digitalWrite(led1, HIGH);
if(data == "off")
digitalWrite(led1, LOW);
}
// Send an event by name
Particle.publish(const char *eventName);
Particle.publish(String eventName);
// Send data via a named event
Particle.publish(const char *eventName, const char *data);
Particle.publish(String eventName, String data);
// Return values
boolean (true or false)
// Example usage
bool success;
success = Particle.publish("button-pressed");
if (!success) {
// triggered if event publish failed
}
void setup()
{
Particle.subscribe("button-pressed", handler);
Serial.begin(9600);
}
void handler(String event, String data)
{
Serial.print(event);
Serial.print(", data: ");
if (data)
{
Serial.print(data);
else
Serial.print("NULL");
}
Serial.println();
}
// Register the pin that the button is
// connected to
int buttonPin = D6;
// Register and Initialise a flag to hold
// current state.
bool pressed = false;
// Register a delay period to slow things
// down if needed.
int period = 100;
// Perform the program setup
void setup()
{
// Set the button pin as an input
pinMode(buttonPin, INPUT);
// Set the pressed flag to false
bool pressed = false;
// Set the initial state of subscriber
// to off just in case.
Particle.publish("ledToggle", "off");
}
// Loop through the program
void loop()
{
// Check to see if the button is pressed
// or not. The use of flags ensures that
// only a singular event is called for
// each state.
if(digitalRead(buttonPin) == LOW)
{
// The button is released. Check against the flag
// to see if it has already been set. If so return.
if(pressed == false)
return;
// The flag has not been set so set it now.
pressed = false;
// Publish the off event.
Particle.publish("ledToggle", "off");
}
else if(digitalRead(buttonPin) == HIGH)
{
// The button is pressed. Check against the flag
// to see if it has already been set. If so return.
if(pressed == true)
return;
// The flag has not been set so set it now.
pressed = true;
// Publish the on event.
Particle.publish("ledToggle", "on");
}
// Use a delay to slow down the loop; thus allowing
// time for operations to complete.
delay(period);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment