库的链接在文章末尾。
#include
#include
//设备连接阿里云的库,非常好用
#include
//解析PZEM-004T数据的库
#include
#include
#include
#include //连接阿里云用到的库
static WiFiClient espClient;
AliyunIoTSDK iot;
//这个库用来解析数据
#include
//设备三元组
#define PRODUCT_KEY "xxxxxxxxxx"
#define DEVICE_NAME "xxxxxxxxxx"
#define DEVICE_SECRET "xxxxxxxxxxxxxxxxxxxxxxxx"
#define REGION_ID "cn-shanghai"
//wifi信息
#define WIFI_SSID "xxxxx"
#define WIFI_PASSWD "xxxxxxxxxxxxxx"
//定义rx、tx两个接口。pzem的tx连接D1、rx连接D2
PZEM004Tv30 pzem(D1,D2);
//初始化wifi信息
void wifiInit(const char *ssid, const char *passphrase)
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, passphrase);
WiFi.setAutoConnect (true);
WiFi.setAutoReconnect (true);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("WiFi not Connect");
}
Serial.println("Connected to AP");
}
unsigned long lastMsMain = 0;
DynamicJsonDocument doc(1024);
void setup() {
Serial.begin(115200);
wifiInit(WIFI_SSID, WIFI_PASSWD);
AliyunIoTSDK::begin(espClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, REGION_ID);
}
void loop() {
AliyunIoTSDK::loop();
if (millis() - lastMsMain >= 3000)
{
lastMsMain = millis();
//获取数据
doc["voltage"] = pzem.voltage();
doc["current"] = pzem.current();
doc["power"] = pzem.power();
doc["energy"] = pzem.energy();
// if( !isnan(voltage)&&!isnan(current)&&!isnan(power)&&!isnan(energy)&&!isnan(frequency)&&!isnan(pf)){
// doc[""voltage"]
// } else {
// Serial.println("Error reading voltage");
// }
String output;
serializeJson(doc, output);
const char *str = output.c_str();
//发送数据,又有send方法的参数为const char*类型,则需要把数据转化为char类型的json数据。
AliyunIoTSDK::send(str);
}
}
arduino-aliyun-iot-sdk
链接
PZEM-004T数据分析
链接