Code:
/* KinCony M1 arduino demo
* output BL0942 voltage,current,power,frequency data by serial port
* @Author: www.kincony.com
*/
#include <SoftwareSerial.h>
const int Cur_mR = 10200; //10200;
const int Volt_mR = 28700; //28700;
unsigned char eNe_state = 0;
unsigned long dp_value_add_ele_1_value = 0;
unsigned long dp_value_cur_current_1_value = 0;
unsigned long dp_value_cur_power_1_value = 0;
unsigned long dp_value_cur_voltage_1_value = 0;
unsigned long dp_value_cur_freq_1_value = 0;
unsigned long dp_value_temp_value = 0;
#define USB_TX_PIN 1
#define USB_RX_PIN 3
#define ENE1_RX_PIN 14
#define ENE1_TX_PIN 13
#define OUT1_PIN 33
unsigned long last_time = 0;
unsigned long eNe_last_time = 0;
String indata="";
String val="";
String outdata="";
SoftwareSerial eNe1;
void setup()
{
pinMode(OUT1_PIN, OUTPUT);
digitalWrite(OUT1_PIN, HIGH);
Serial2.begin(9600,SERIAL_8N1,USB_RX_PIN,USB_TX_PIN);
eNe1.begin(9600, SWSERIAL_8N1, ENE1_RX_PIN, ENE1_TX_PIN, false, 64);
eNe1.listen();
last_time = millis();
eNe_last_time = last_time;
eNe_state = 0;
}
void loop()
{
//sample energy
switch (eNe_state)
{
case 0:
if((millis() - eNe_last_time)>100)
{
eNe1.listen();
eNe_state=1;
eNe_last_time = millis();
}
break;
case 1:
if((millis() - eNe_last_time)>1000)
{
eNe_state=2;
eNe_last_time = millis();
}
break;
case 2:
outdata = "12";
outdata[0] = 0x58;
outdata[1] = 0xAA;
eNe1.print(outdata);
eNe_state=3;
eNe_last_time = millis();
break;
case 3:
if(eNe1.available()>0)
{
indata+=char(eNe1.read()); //read ene1
eNe_last_time = millis();
}
else
{
if(((millis() - eNe_last_time)>4)&&(indata.length()>2))
{
val=indata; //
dp_value_add_ele_1_value=(double(indata[13]+indata[14]*256+indata[15]*65536)*16384*256*1218*1218*22*5)/36000/3537/Cur_mR/Volt_mR; //10200mR 28700mR
dp_value_cur_current_1_value=(double(indata[1]+indata[2]*256+indata[3]*65536)*1218*1000)/305978/Cur_mR; //10200mR
dp_value_cur_power_1_value=(double(indata[10]+indata[11]*256+indata[12]*65536)*1218*1218*22*5)/3537/Cur_mR/Volt_mR; //10200mR 28700mR
dp_value_cur_voltage_1_value=(double(indata[4]+indata[5]*256+indata[6]*65536)*1218*22*5)/73978/Volt_mR; //28700mR
dp_value_cur_freq_1_value=2*500000/(double(indata[16]+indata[17]*256+indata[18]*65536)); //
Serial2.println("meter1 channel data:");
Serial2.print("ele1:");
Serial2.print(dp_value_add_ele_1_value);
Serial2.println(" wh");
Serial2.print("current1:");
Serial2.print(dp_value_cur_current_1_value);
Serial2.println(" mA");
Serial2.print("power1:");
Serial2.print(dp_value_cur_power_1_value);
Serial2.println(" W");
Serial2.print("voltage1:");
Serial2.print(dp_value_cur_voltage_1_value);
Serial2.println(" V");
Serial2.print("freq1:");
Serial2.print(dp_value_cur_freq_1_value);
Serial2.println(" Hz");
eNe_state=0;
indata="";
eNe_last_time = millis();
}
}
break;
delay(1000);
}
}