Hello, I'm trying to connect a energy meter (see attached image) to a NodeMCU ESP8266 and post the power to Thingspeak. I have manage to post a temperature from a DHT22 to Thingspeak with NodeMCU and I have managed to read the power from the energy meter with a Arduino UNO. But I can't combine this two projects =(
I think the problem is the interrupt function in combination with the post-request to Thingspeak but I'm not sure how I should handle this. I get the following out from the serial monitor:
"len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
Client connected ...Connected
1953 30
1947 50
1943 70"
So, I get the power and the watt-hour (1953 W, 30 Wh) but nothing at Thingspeak. Maybe I'm running out of memory?
My Arduino Code:
#include <ESP8266WiFi.h>
const char* server = "api.thingspeak.com";
String apiKey ="DUG0GBLHZUGXO55J";
const char* MY_SSID = "Mattiass iPhone";
const char* MY_PWD = "12341235";
long pulseCount = 0; //Number of pulses, used to measure energy.
unsigned long pulseTime,lastTime; //Used to measure power.
float power, elapsedkWh; //power and energy
float ppwh = 0.1; //Number of pulses per wh - found or set on the meter.//1000 pulses/kwh = 1 pulse per wh
// The interrupt routine
void onPulse() {
lastTime = pulseTime;
pulseTime = micros();
pulseCount++;
power = (3600000000.0 / (pulseTime - lastTime))/ppwh; //Calculate power
elapsedkWh = (1.0*pulseCount/(ppwh /* *1000*/)); //Find kwh elapsed //multiply by 1000 to convert pulses per wh to kwh
Serial.print(power,0);
Serial.print(" ");
Serial.println(elapsedkWh,0);
//if((pulseTime/1000000 - lastTime/1000000) > 15){
WiFiClient client;
if (client.connect("api.thingspeak.com", 80)) { // use ip 184.106.153.149 or api.thingspeak.com
Serial.println("WiFi Client connected ");
String postStr = apiKey;
postStr += "&field1=";
postStr += String(power);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
}//end if
client.stop();
// }
}
void setup()
{
Serial.begin(115200);
Serial.print("Connecting to "+*MY_SSID);
WiFi.begin(MY_SSID, MY_PWD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected");
delay(5000);
attachInterrupt(digitalPinToInterrupt(4), onPulse, FALLING); // KWH interrupt attached to IRQ 1 = pin3
}
void loop()
{
}