Posts: 6,843
Threads: 4
Joined: Mar 2015
#include <LiquidCrystal.h>
#include <ModbusMaster.h>
#define METERSLAVEID 11
#define LEDPIN 13
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
// Create a software interface for meter (create a ModBusMaster node)
ModbusMaster node(METERSLAVEID);
void setup() {
// Initialising communication with meter
node.begin(9600);
// Setting up led
pinMode(LEDPIN, OUTPUT);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
//set data output enable pin to output mode
}
void loop() {
// Reading data from meter
// 1. Request data using readHoldingRegisters() (i think we need to enable the outputs before this)
// 2. Check whether data is available using node.ku8MBSuccess flag
// 3. If valid read data from buffer using node.getResponseBuffer()
uint16_t data[ 2]; //We are using array of two 16 bit because we are reading two registers of 16 bit from meter
uint8_t flag; //8 bit flag is required for error checking because we get 8 bit status
int final; //final result
//see comment 1
flag = node.readInputRegisters(30001, 2);
lcd.setCursor(0, 1);
// print the number of seconds since reset:
switch(flag)
{
case 0x01:
lcd.print("Illegal Function");
break;
case 0x02:
lcd.print("Illegal DataAddress");
break;
case 0x03:
lcd.print("Illegal DataValue");
break;
case 0x04:
lcd.print("Slave device Failure");
break;
case 0x00:
lcd.print("Success");
break;
case 0xE0:
lcd.print("Invalud Slave");
break;
case 0xE1:
lcd.print("Invalid Function");
break;
case 0xE2:
lcd.print("Time Out");
break;
case 0xE3:
lcd.print("Invalid CRC");
break;
}
if(flag == node.ku8MBSuccess){
//glow a led
digitalWrite(LEDPIN, HIGH);
//read data
data[0] = node.getResponseBuffer(0);
data[1] = node.getResponseBuffer(1);
final = data[0];
if(data[1] == 0xFFFF) //sign check
{
final = (~data[0]) + 1;
final = final * (-1);
}
}
else{
//unglow a led
digitalWrite(LEDPIN, LOW);
}
delay(1000);
}