Application Code

Here is the entire application code put together.

/*----------------------------------------------------------------
Title: Blynk Relay Tutorial 
Written By: (Place Your Name Here)
Date Written: (Place Date here)
Description: This code was written to control 4 individual relays
on an Particle Argon Relay Shield using four switch widgets on a 
Blynk web interface and moblile app.

Blynk Data Streams:
Relay 1 (V0)
Relay 2 (V1)
Relay 3 (V2)
Relay 4 (V3)
----------------------------------------------------------------------*/
// Firmware Configuration
#define BLYNK_TEMPLATE_ID "Enter your template ID here"
#define BLYNK_DEVICE_NAME "Enter your device name here"
#define BLYNK_AUTH_TOKEN  "Enter your device auth token here"

#include <blynk.h> //Blynk library 

// Global Variables
char auth[] = BLYNK_AUTH_TOKEN; // defines the character array auth
const int relayPins[] = {5, 6, 7, 8}; //defines the relay pins in an array as constant intgers
const int relay1 = 5; // variable for controlling digital I/O pin 5 on the Argon
const int relay2 = 6; // variable for controlling digital I/O pin 6 on the Argon
const int relay3 = 7; // variable for controlling digital I/O pin 7 on the Argon
const int relay4 = 8; // variable for controlling digital I/O pin 8 on the Argon
volatile int relayState1 = LOW; // volatile variable for reading the current state of the relay, also setting it to LOW 
volatile int relayState2 = LOW;
volatile int relayState3 = LOW;
volatile int relayState4 = LOW;

void setup()
{
    // This code runs once on startup
    for(int i=0; i<4; i++){ 
    // for loop for setting each I/O pin mode as an output
        pinMode(relayPins[i], OUTPUT);
        digitalWrite(relayPins[i], LOW);
    }
    delay(5000);
    Blynk.begin(auth); // connect to blynk cloud using auth token
}
void loop()
{
    // This code runs continuosuly
    Blynk.run(); // runs the Blynk API
}
BLYNK_WRITE(V0)
{
    if(param.asint() != relayState1)
    {
        relayState1 = !relayState1; // Toggle state
        // set the relay output pin to the state of the of relayState1 variable
        digitalWrite(relay1, relayState1); 
}
BLYNK_WRITE(V1)
{
    if(param.asint() != relayState2)
    {
        relayState2 = !relayState2; // Toggle state
        // set the relay output pin to the state of the of relayState2 variable
        digitalWrite(relay2, relayState2); 
}
BLYNK_WRITE(V2)
{
    if(param.asint() != relayState3)
    {
        relayState3 = !relayState3; // Toggle state
        // set the relay output pin to the state of the of relayState3 variable
        digitalWrite(relay3, relayState3); 
}
BLYNK_WRITE(V3)
{
    if(param.asint() != relayState4)
    {
        relayState4 = !relayState4; // Toggle state
        // set the relay output pin to the state of the of relayState4 variable
        digitalWrite(relay4, relayState4); 
}

Last updated