Complete code
// The Basis of this Code was take from: https://github.com/ControlEverythingCommunity/PECMAC/blob/master/Particle/PECMAC125A.ino
// By Ryan Fontaine, P.E.
/*
1. Purchase CT Board from ControlEverything.com - https://shop.controleverything.com/collections/energy-monitoring/products/4-channel-off-board-ac-current-monitor-for-particle-electron
2. Create a free account at www.ThingSpeak.com
3. Create a Webhook manually at https://console.particle.io/integrations/webhooks/create
Click [CUSTOM JSON] at the Top Right
Copy/Paste the following into the JSON window:
{
"event": "TEST",
"url": "https://api.thingspeak.com/update",
"requestType": "POST",
"form": {
"api_key": "{{k}}",
"field1": "{{1}}",
"field2": "{{2}}",
"field3": "{{3}}",
"field4": "{{4}}",
"field5": "{{5}}",
"field6": "{{6}}",
"field7": "{{7}}",
"field8": "{{8}}",
"lat": "{{a}}",
"long": "{{o}}",
"elevation": "{{e}}",
"status": "{{s}}"
},
"mydevices": true,
"noDefaults": true
}
You will change the "event" in the first line of the JSON to whatever event name you wish:
The Example names the WebHook's event: "TEST",
So you would change the CODE (for Photon or Electron) below under [Specific Values for each Installation] to :
const char * eventName = "TEST"
To match the WebHook event name.
*OR* Follow these instructions : https://www.hackster.io/15223/thingspeak-particle-photon-using-webhooks-dbd96c
4. Change the other values below, under [Specific Values for each Installation] , per your requirements
5. Flash Firmware to Photon/Electron
6. If you want Notifications on your cell phone when a Pump Starts/Stops, then Create an IFTTT.com account.
The format is
If THIS : type Particle
for TRIGGER choose : New Event Published
If (Event Name) : type PUMP
is (Event Contents) : *Leave This BLANK*
Device Name or ID : Choose your Particle Device from the DropDown list
Click CREATE TRIGGER
CLick THAT
Search for NOTIFICATIONS or SMS (note: you can have unlimited notifications per month, but only 100 SMS text messages per month) Notifications Recommended , & download the IFTTT app to your phone.
Click CREATE TRIGGER.
7. Use Mobicle.IO to change the Publish Delay "On-The-Fly" without needing to Flash Firmware (see bottom of CODE). Very Useful to "fine-tune" the data usage of ELECTRONS that are installed remotely.
8. Use Mobicle.IO to remotely RESET the Particle Device if needed (see bottom of CODE)
*/
// [ Specific Values for each Installation ]
//////////////////////////////////////////////////////
const char * eventName = "TEST"; // This must match the name of the event you chose for the WebHook in Step #3
int publish_delay = 30000; // Multiply # of Seconds * 1000. This is how often the AMPS will be updated on ThingSpeak.com while a pump is running. Very Important to data usage for an ELECTRON. Start with 180000 after initial bench testing..
int minCurrent = 20; // MUST MULTIPLY BY A FACTOR OF 10. Example: using 20 will eleminate any AMP Reading that is less than 2 AMPS to avoid noise on the Graph.
int spikeCurrent = 500; // MUST MULTIPLY BY A FACTOR OF 10. Example: using 500 will eleminate any AMP Reading that is OVER 50 AMPS. This doesn't show Startup SPIKES for large Inductive Loads, true running amps will be read 10 seconds later.
// If you dont want the minCurrent and spikeCurrent Functionality, set to 1 and 1500 respectively
//ThingSpeak Channel Info //
const char * myWriteAPIKey = "XXXXXXXXXXXXXXXX"; // From your ThinkSpeak Account Info (API KEYS tab)
//////////////////////////////////////////////////////
// There is no need to change anything else if you are just getting started.
#include <spark_wiring_i2c.h>
#include <application.h>
#define AddrCurrent 0x2A // I²C Address for Current Monitor
#define CT_delay 10000 // 10,000 = 10 seconds. The CT Current Monitor Data Sheet suggests only reading the Board every 8-10 seconds
SYSTEM_THREAD(ENABLED);
char msg[256];
unsigned long now = millis(); // Used as Time to compare the Ellapsed time for various readings
unsigned int lastPublish = 0; // Previous Publish to ThingSpeak
unsigned long nowCT = millis(); // Latest CT Current-Monitor Reading
unsigned int lastCT = millis(); // Previous CT Current-Monitor Reading
// Variables Req'd for I²C CT Current-Monitor Board
int msb1 = 0, msb = 0, lsb = 0;
unsigned int data[36];
int typeOfSensor = 0;
int maxCurrent = 0;
int noOfChannel = 0;
double current = 0;
double amps = 0;
// These 4 Floats will hold the values to send to ThinkSpeak.com for data logging to the Cloud :
float CH1, CH2, CH3, CH4; // Pump/Motor AMPS
// Arrays
static int oldVal[5] = {0,0,0,0,0}; // Previous Sensor Values to Compare if Run State has Changed - equality checks are safer with Integers, so we will multiply by 10 for all sensor values, But divide by 10 before publishing each value
static int nowVal[5] = {0,0,0,0,0}; // Most Recent Sensor Values * 10
static int Flag[3] = {0,0,0}; // A "0" Value means nothing to update. Flag[1] = 1 requests to Publish AMPS after the Publish Delay, Flag[2] = 1 requests an immediate Publish (no Delay - used for Pump Start/Stop Events)
// Remote Reset Function, used to RE-SET the Photon/Electron using www.Mobicle.io
#define DELAY_BEFORE_REBOOT 2000
unsigned int rebootDelayMillis = DELAY_BEFORE_REBOOT;
unsigned long rebootSync = millis();
bool resetFlag = false;
void setup() {
// Register Particle Function to allow user to remotely Change the Publish Delay.
Particle.function("setDelay", setPublishDelay);
// Set I²C Current Monitor Board variable
Particle.variable("i2cdevice", "PECMAC125A");
Particle.variable("typeOfSensor", typeOfSensor);
Particle.variable("maxCurrent", maxCurrent);
Particle.variable("noOfChannel", noOfChannel);
// Remote Reset Function
Particle.function("reset",cloudResetFunction);
// I²C setup for the CT Current-Monitor Motherboard
// Initialise I²C communication as MASTER
Wire.begin();
// Initialise Serial Communication, set baud rate = 9600
Serial.begin(9600);
// Setup the Current Monitor
// Start I²C transmission
Wire.beginTransmission(AddrCurrent);
// Command header byte-1
Wire.write(0x92);
// Command header byte-2
Wire.write(0x6A);
// Command 2 is used to read no of sensor type, Max current, No. of channel
Wire.write(0x02);
// Reserved
Wire.write(0x00);
// Reserved
Wire.write(0x00);
// Reserved
Wire.write(0x00);
// Reserved
Wire.write(0x00);
// CheckSum
Wire.write(0xFE);
// Stop I²C transmission
Wire.endTransmission();
// Request 6 bytes of data
Wire.requestFrom(AddrCurrent, 6);
// Read 6 bytes of data
if (Wire.available() == 6){
data[0] = Wire.read();
data[1] = Wire.read();
data[2] = Wire.read();
data[3] = Wire.read();
data[4] = Wire.read();
data[5] = Wire.read();
}
typeOfSensor = data[0];
maxCurrent = data[1];
noOfChannel = data[2];
delay(200);
}
void loop() {
// Read all channels of Current-Monitor // The CT's measure the AMPS on each channel. # of Channels depends on the Actual Current Monitor Board Purchased.
// This code works for up to 4 Channels, but you can easily use a 6 channel CT Board and increase the oldVal and nowVal Arrays and add the CH's for the Particle.Publish lines.
nowCT = millis();
if (abs(nowCT - lastCT) > CT_delay) { // The intention is to only read the Current Monitor every 10 seconds, per the Specs.
for (int j = 1; j < noOfChannel + 1; j++) {
// Start I²C Transmission
Wire.beginTransmission(AddrCurrent);
// Command header byte-1
Wire.write(0x92);
// Command header byte-2
Wire.write(0x6A);
// Command 1
Wire.write(0x01);
// Start Channel No.
Wire.write(j);
// End Channel No.
Wire.write(j);
// Reserved
Wire.write(0x00);
// Reserved
Wire.write(0x00);
// CheckSum
Wire.write((0x92 + 0x6A + 0x01 + j + j + 0x00 + 0x00) & 0xFF);
// Stop I²C Transmission
Wire.endTransmission();
delay(1000);
// Request 3 bytes of data
Wire.requestFrom(AddrCurrent, 3);
// Read 3 bytes of data
// msb1, msb, lsb
msb1 = Wire.read();
msb = Wire.read();
lsb = Wire.read();
current = (msb1 * 65536) + (msb * 256) + lsb;
// Convert the data to ampere
amps = current / 1000;
// the For Loop cycles through each Channel of the CT Board. Store each AMP reading next.
nowVal[j] = round(amps * 10) ; // Multiply the AMPS * 10 and store the value in the Array for that particular Channel (CH1 - CH4). This converts the AMP reading to an integer, we will "recover" the decimal place later.
if (nowVal[j] > spikeCurrent){ // Want to eleminate the SPIKE during Startup. The CT will recognize the TRUE Running Amps 10 seconds (CT_Delay) later during the next read and store that value instead.
nowVal[j] = 0; // set to 0 and read the True Running Amps on the Next read in 10 seconds.
}
if (nowVal[j] < minCurrent) { //The CT's may bounch around 0-2 amps during "No-Load".
nowVal[j] = 0; // Dont want to send 0.XX - 2.00 Amps to ThingSpeak, so delete these low values, or "noise".
if (oldVal[j] > minCurrent) { // If the previous AMP reading showed the Pump to be Running, but Now it is NOT Running- So the PUMP just "STOPPED".
Particle.publish("PUMP", "Pump # " + String(j) + " Stopped" , PRIVATE); // Comment Out this line if you do Not Want Start/Stop Notifications. Use IFTTT.com if you do.
Flag[2] = 1; // Will REQUEST an immediate full publish - with no publish Delay Check for Flag[2] == 1.
}
}
// Same as above, but checking to see if the Pump JUST "STARTED".
if (nowVal[j] > minCurrent) { //The CT's bounch around 0 amps. Dont want to send 0.XX - 2.00 Amps to ThingSpeak
Flag[1] = 1; // Flag[1] is used for ANY CT measurement above the minimum threshold - Requests a Full Publish after the Publish Delay Is Met. This is to log normal runtime AMPS at the interval publish_delay.
if (oldVal[j] < minCurrent) { // a PUMP is running now but wasn't on previous check, then it just "STARTED".
Particle.publish("PUMP", "Pump # " + String(j) + " Started" , PRIVATE); // Comment Out this line if you do Not Want Start/Stop Notifications. Use IFTTT.com if you do.
Flag[2] = 1; // Will REQUEST an immediate full publish - with no publish Delay Check for Flag[2] == 1
}
}
oldVal[j] = nowVal[j]; // Set the Old Value to the most recent Value for the Next Comparison to determine if the Pump is Starting or Stopping.
}
lastCT = nowCT; // Since we've sucessfully read all the Channels of the CT Current Monitor Board, update the TIME for the Last Read. We want to wait 10 seconds before another CT Current Monitor Board Read.
}
// ALL READINGS ARE COMPLETE, SO UPDATE THE CHANNEL Float Values used for logging data to www.THINGSPEAK.COM
CH1 = (nowVal[1] / 10.0); // Divide each Integer Value by 10 to recover the 1 Decimal Place precision
CH2 = (nowVal[2] / 10.0);
CH3 = (nowVal[3] / 10.0);
CH4 = (nowVal[4] / 10.0);
// Check Flag[2]; requests a publish when a pump has started/stopped. No Publish Delay (other than ThingSpeak.com 15 sec). Allows the "normal" publish delay to be longer for updating the AMPS during a Pump Run.
if (Flag[2] == 1) {
now = millis();
if (abs(now - lastPublish) > 30000) { // 15 Seconds is the fastest Update Rate for a ThingSpeak Channel.
// Build the Particle Publish String
// The next 3 lines are the same as this: snprintf(msg, sizeof(msg), "{\"1\":\"%.1f\",\"2\":\"%.1f\",\"3\":\"%.1f\",\"4\":\"%.1f\",\"k\":\"%s\"}", CH1, CH2, CH3, CH4, myWriteAPIKey); just formmatted for easier reading.
snprintf(msg, sizeof(msg),
"{\"1\":\"%.1f\" , \"2\":\"%.1f\" , \"3\":\"%.1f\" , \"4\":\"%.1f\" , \"k\":\"%s\"}",
CH1 , CH2 , CH3 , CH4 , myWriteAPIKey);
// Particle.publish(eventName, msg, PRIVATE); // Publish with Acknowledgement
Particle.publish(eventName, msg, PRIVATE, NO_ACK); // Publish with NO Acknowledgement to save Electron Data
lastPublish = now;
Flag[1] = 0; // Reset Flag- just published.
Flag[2] = 0; // Reset Flag- just published.
}
}
// Check Flag[1], this is the normal publish during runtime
if (Flag[1] == 1) {
now = millis();
if (abs(now - lastPublish) > publish_delay) { // Wont publish more often than publish_delay.
snprintf(msg, sizeof(msg),
"{\"1\":\"%.1f\" , \"2\":\"%.1f\" , \"3\":\"%.1f\" , \"4\":\"%.1f\" , \"k\":\"%s\"}",
CH1 , CH2 , CH3 , CH4 , myWriteAPIKey);
// Particle.publish(eventName, msg, PRIVATE); // Publish with Acknowledgement
Particle.publish(eventName, msg, PRIVATE, NO_ACK); // Publish with NO Acknowledgement to save Electron Data
lastPublish = now;
Flag[1] = 0; // Reset Flag- just published.
Flag[2] = 0; // Reset Flag- just published.
}
}
// FAILSAFE every 20 MINUTES
// The ELECTRON will Handshake the Cellular Tower every 22-23 minutes if no data has been sent, which uses 70+ Bytes of Data Overhead, So we will publish actual Data every 20 minutes and not waste Cellular data with the empty "Ping" every 22 minutes.
now = millis();
if (abs(now - lastPublish) > 1200000) {
snprintf(msg, sizeof(msg),
"{\"1\":\"%.1f\" , \"2\":\"%.1f\" , \"3\":\"%.1f\" , \"4\":\"%.1f\" , \"k\":\"%s\"}",
CH1 , CH2 , CH3 , CH4 , myWriteAPIKey);
Particle.publish(eventName, msg, PRIVATE); // Publish with Acknowledgement since this is a 20 minute failsafe "Check-in"
lastPublish = now;
Flag[1] = 0; // Reset Flag- just published.
Flag[2] = 0; // Reset Flag- just published.
}
// Remote Reset Function, Use Mobicle.IO to remotely RE-SET the Photon/Electron easily. Create a Button that Sends TRUE argument to the Function
if ((resetFlag) && (millis() - rebootSync >= rebootDelayMillis)) {
Particle.publish("Debug","Remote Reset Initiated",300,PRIVATE);
System.reset();
}
} // End LOOP
// Remote Reset Function
int cloudResetFunction(String command) {
resetFlag = true;
rebootSync=millis();
return 0;
}
//Funciton to change the Publish Delay remotely, without needing to reflash the Firmware. Use Mobicle.IO
int setPublishDelay(String command) {
//Particle.functions take a string as an argument
publish_delay = ( command.toInt() * 60000 );
// Use Mobicle.Io
// Select Device, then Create a Button to send the # of MINUTES as an Argument to the setPublishDelay FUNCTION.
// Create as Many buttons as you need, or you can type the Argument direcly into the Function.
// Value must be an Integer....1,2,3, etc in Minutes.
}