Raspberry Pi ModBus Energy Meter 1

 

Needed 
1 RaspberryPI
1 EJS 212 D2AMX Energy meter with ModBus
1 USB<>RS485 Converter
1 twisted pair cable
recommend install Raspbian

 

 

 

Set speed USB port - 9'600 bps, 8E1

 

stty -F /dev/ttyUSB0 9600 cs8 parenb -parodd

 

 

C code

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
 
int main(int argc, char* argv[]) {
 
    struct termios serial;
    char inBuff[16];
    char *buffer;
    char choice[5];
    int wcount = 0;
    char rdINPUT[8]= {0x22,0x04,0x00,0x00,0x00,0x06,0x77,0x5B};
    int fd = open("/dev/ttyUSB2", O_RDWR | O_NOCTTY | O_NDELAY);
    double tariff1,tariff2,tariff3;
 
    if (fd == -1) {
        perror(argv[2]);
        return -1;
    }
 
    if (tcgetattr(fd, &serial) < 0) {
        perror("Getting configuration");
        return -1;
    }
 
    //////////////////// Set up Serial Configuration ////////////
    serial.c_iflag = 0;
    serial.c_oflag = 0;
    serial.c_lflag = 0;
    serial.c_cflag = 0;
 
    serial.c_cc[VMIN] = 0;
    serial.c_cc[VTIME] = 10;
 
    serial.c_cflag = B9600 | CS8 | PARENB | CREAD & ~PARODD;
    fcntl(fd,F_SETFL,0);
    tcsetattr(fd, TCSANOW, &serial); // Apply configuration
    //////////////////////////////////////////////////////////////
 
    
   int rcount;  
   buffer = &inBuff[0];
   int i = 0;
   int j = 0;
   write(fd,rdINPUT,8);
   buffer = &inBuff[0];
 
   printf("Send: ");
   for(j = 0;j < sizeof(rdINPUT);j++)
   {
printf("%02x ",rdINPUT[j]);
   }
   printf("\r\n");
   printf("Received: " );
while( (rcount = read(fd,buffer,1)) > 0)
{
      if (rcount < 0) {
           perror("Read");
          return -1;
        }
 
      buffer++;
printf("%02x ",inBuff[i]); i++;
  }
       tariff2 =(double)(256*256*256*inBuff[3]) + (double)(256*256*inBuff[4]) + (double)(256*inBuff[5]) + (double)inBuff[6];
       tariff2 =(double)(256*256*256*inBuff[7]) + (double)(256*256*inBuff[8]) + (double)(256*inBuff[9]) + (double)inBuff[10];
       tariff1 =(double)(256*256*256*inBuff[11]) + (double)(256*256*inBuff[12]) + (double)(256*inBuff[13]) + (double)inBuff[14];
       printf("\r\n");
       printf("Peak Tariff 3: %4.3f KWh",tariff3/100);
       printf("\r\n");
       printf("Daily Tariff 2: %4.3f KWh",tariff2/100);
       printf("\r\n");
       printf("Night Tariff 1: %4.3f KWh",tariff1/100);
       printf("\r\n");
 
close(fd);
}
 

 

 

 

 

Input Registers

Address

Value

0x00

Energy tariff 3 - peak (most significant part)

0x01

Energy tariff 3 - peak (low significant part)

0x02

Energy tariff 2 - peak (most significant part)

0x03

Energy tariff 2 - peak (low significant part)

0x04

Energy tariff 1 - peak (most significant part)

0x05

Energy tariff 1 - peak (low significant part)

 

Note: All values ​​of the energy registers are in hundredths of KWh, 1 from the register corresponds to 0.01 KWh

 

 

 

 

 
 
 
 
Read 16447 times