Advertisement
mikroavr

pzem_1channel

Mar 12th, 2023
789
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. #include <ModbusMaster.h>
  3. ModbusMaster node;
  4.  
  5. #define MAX485_RXD 17
  6. #define MAX485_TXD 16
  7.  
  8. #define led 23
  9. bool stateLed = 0;
  10.  
  11. byte addr_pzem = 1;
  12.  
  13. unsigned long cur_time, old_time;
  14. float voltage,  current, power, energy, freq, pf;
  15.  
  16. int waktu = 30;
  17.  
  18. void setup() {
  19.   // put your setup code here, to run once:
  20.   delay(100);
  21.   pinMode(led, OUTPUT);
  22.   Serial.begin(115200);
  23.   Serial1.begin(9600, SERIAL_8N1, MAX485_RXD, MAX485_TXD);
  24.   node.begin(addr_pzem, Serial1);
  25.  
  26. }
  27.  
  28. void loop() {
  29.   // put your main code here, to run repeatedly:
  30.   cur_time = millis();
  31.   if (cur_time - old_time >= 250) {
  32.     baca_pzem();
  33.     stateLed = !stateLed;
  34.     digitalWrite(led, stateLed);
  35.     old_time = cur_time;
  36.   }
  37. }
  38.  
  39. void baca_pzem() {
  40.   uint8_t result;
  41.   result = node.readInputRegisters(0, 9); //read the 9 registers of the PZEM-014 / 016
  42.   if (result == node.ku8MBSuccess)
  43.   {
  44.     Serial.println("sukses modbus");
  45.     voltage = node.getResponseBuffer(0) / 10.0;
  46.  
  47.     uint32_t tempdouble = 0x00000000;
  48.  
  49.     tempdouble = node.getResponseBuffer(1);       //LowByte
  50.     tempdouble |= node.getResponseBuffer(2) << 8;  //highByte
  51.     current = tempdouble / 1000.0;
  52.  
  53.     tempdouble |= node.getResponseBuffer(3);       //LowByte
  54.     tempdouble |= node.getResponseBuffer(4) << 8;  //highByte
  55.     power = tempdouble / 10.0;
  56.  
  57.     tempdouble = node.getResponseBuffer(5);       //LowByte
  58.     tempdouble |= node.getResponseBuffer(6) << 8;  //highByte
  59.     energy = tempdouble;
  60.  
  61.     tempdouble = node.getResponseBuffer(7);
  62.     freq = tempdouble / 10.0;
  63.  
  64.     tempdouble = node.getResponseBuffer(8);
  65.     pf = tempdouble / 10.0;
  66.     print_data();
  67.  
  68.   } else {
  69.     Serial.println("Failed to read modbus");
  70.   }
  71.  
  72. }
  73.  
  74. void print_data() {
  75.   Serial.print(voltage);
  76.   Serial.print("V   ");
  77.  
  78.   Serial.print(current);
  79.   Serial.print("A   ");
  80.  
  81.   Serial.print(freq);
  82.   Serial.print("Hz   ");
  83.  
  84.   Serial.print(pf);
  85.   Serial.print("pf   ");
  86.   Serial.print("   ");
  87.  
  88.   Serial.print(power);
  89.   Serial.print("W  ");
  90.  
  91.   Serial.print(energy);
  92.   Serial.print("Wh  ");
  93.   Serial.println();
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement