RS-485 modbus library


#61

Here is the piece of code that I use to read a few VFD modbus holding registers.
I use this library… I have no made any modification to the code: Github user 4-20ma "Modbus Master"
see the modbus master files inside src folder, notice I copy crc16.h and word.h to the same folder.

#include <ModbusMaster.h>

/*!
  We're using a MAX485-compatible RS485 Transceiver.
  Rx/Tx is hooked up to the hardware serial port at 'Serial'.
  The Data Enable and Receiver Enable pins are hooked up as follows:
*/
#define MAX485_DE      A3
#define MAX485_RE_NEG  A2
#define CT_VFD(m,n)  (m *100+ n-1)  // formula to acces VFD registers (not used in this example)
// Comment this out if you don't want serial output
#define DEBUGON 1

// Transmission delay between modbus calls
#define XMITDELAY 2000

// 0 for 0-based, 1 for 1-based numbering
#define BASED_NUMBERING 1

/*********
* Retreives holding register data while handling device sleeping conditions
**********/

// instantiate ModbusMaster object
ModbusMaster node;
#define reg_qty 11 (not used in this example)
void preTransmission()
{
  digitalWrite(MAX485_RE_NEG, 1);
  digitalWrite(MAX485_DE, 1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);
}

void setup()
{
  pinMode(MAX485_RE_NEG, OUTPUT);
  pinMode(MAX485_DE, OUTPUT);
  // Init in receive mode
  digitalWrite(MAX485_RE_NEG, 0);
  digitalWrite(MAX485_DE, 0);

  // Modbus communication runs at 115200 baud
  Serial.begin(19200);
  Serial1.begin(19200);
  // Modbus slave ID 1, Serial1 on the Particle Photon
  node.begin(1, Serial1);
  // Callbacks allow us to configure the RS485 transceiver correctly
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

bool state = true; // (not used in this example)

void loop()
{
  uint16_t data[6];
  
 getHoldingRegisterData( 407,  1,  data);  //symetrical current limit in % 0.1 dec place
 delay(1000);
 getHoldingRegisterData( 506,  1,  data); //motor rated frecuency in hz 0.1 dec place

}

bool getHoldingRegisterData(uint16_t registerAddress, uint16_t regSize, uint16_t* data){

uint8_t j, result;

if(DEBUGON){
  Serial.print(F("Reading register: "));
  Serial.print(registerAddress);
  Serial.print(F(" regSize: "));
  Serial.print(regSize);
  Serial.print(F(" sizeof(data): "));
  Serial.print(sizeof(&data));
  Serial.print(F(" XMITDELAY: "));
  Serial.println(XMITDELAY);
  Serial.println("");
}

// Delay and get register data.

result = node.readHoldingRegisters(registerAddress-BASED_NUMBERING, regSize);
delay(XMITDELAY);

// LT is sleeping, ping it a couple more times.

if(result ==node.ku8MBResponseTimedOut){

        if(DEBUGON){
          Serial.println(F("LT: Response timed out. Trying again. "));
        }

		int i =0;

		while(i < 2){

			result = node.readHoldingRegisters(registerAddress-BASED_NUMBERING, regSize);
			delay(XMITDELAY);

			if(DEBUGON){
				Serial.printlnf("LT: Timeout iteration# %d. ", i);
			}

			if(result == node.ku8MBResponseTimedOut){
				if(DEBUGON) Serial.println(F("LT: Failed. Response timed out. Adjust the XMITDELAY and/or ku8MBResponseTimeout? "));
			}
			else break;

			i++;

		}

}

if (result == node.ku8MBSuccess) {
  if(DEBUGON){
    Serial.print(F("LT: Success, Received data: "));
  }

  for (j = 0; j < regSize; j++) {

    data[j] = node.getResponseBuffer(j);
    if(DEBUGON){
      Serial.print(data[j], DEC);
      Serial.print(F(" "));
    }
  }

  if(DEBUGON){
	  Serial.println("");
  }

  node.clearResponseBuffer();
  node.clearTransmitBuffer();
  return true;

}
else{
  if(DEBUGON){
	Serial.print(F("Failed, Response Code: "));
	Serial.println(result, HEX);
  }
}

node.clearResponseBuffer();
node.clearTransmitBuffer();
return false;
}


#62

hi @rama what is you recommendation to efficiently program routine to read all this registers and then store the result in structure or an array?

is this the right whay to do it?

int regs[24]={200,400,401,403,416,418,419,425,500,501,502,503,504,703,704,733,734,1039,1810,1811,1812,1813,1814,1815};
 int regs_data[24];
uint8_t k;
uint8_t j;
 for (k = 0; k < 24; k++) {
getHoldingRegisterData( regs[k],  1,  data);  //symetrical current limit in % 0.1 dec place
delay(100);
  for (j = 0; k < 24; j++) {
    regs_data[j]=data[0];
  }
delay(100);
 }




#63

@luisgcu that last was bad… this is the right way to do it…

uint8_t k;
 for (k = 0; k < 24; k++) {
getHoldingRegisterData( regs[k],  1,  data); 
 delay(100);
    regs_data[k]=data[0];
    Serial.printf("Register data : %d: ", regs[k]);
    Serial.print(regs_data[k], DEC);
    Serial.println(F(" "));
 }


#64

@luisgcu It’s -1 because you’re using a uint16_t datatype. It needs to be converted.

I’ll create an extension library for ModbusMaster and add it to my Github. I’m trying to figure this out myself.

Since most modbus prototcol sets are tabular and they have a pattern of Register Address, register size, and description, I can write a simple Python script that can output a data struct I can copy over.

This is what I’m experimenting with currently on my Modbus project. The code may not be the right way, although it may show the logic.

enum rgDTYPE{
  RG16BITS = 1,
  RG32BITS = 2,
  RGCHAR = 2,
  RGSHORT = 2,
  RGUSHORT = 2,
  RGLONG = 4,
  RGULONG = 4,
  RGFLOAT = 4,
  RGTIME = 6,
  RGDOUBLE = 8,
  RGSTRING = 32,
};

typedef struct _rgRegister {
    uint16_t regAddress;
    uint16_t  regSize;
    rgDTYPE  dataType;
    char  desc[30];
} rgRegister;

static const rgRegister PROGMEM _rgDeviceCommonTable[] = {

  {9010, 1, RGUSHORT, "MaxDataLogs"},
  {9011, 2, RGULONG, "TotDataLogMem"},
  {9013, 3, RGULONG, "TotBattTicks"},
  {9019, 32, RGSTRING, "DeviceName"},
  {9051, 32, RGSTRING, "SiteName"},
  {9097, 3, RGTIME, "CurrTimeUTC"},
  {9100, 2, RG32BITS, "DeviceStatus"},
  {9102, 2, RGULONG, "UsedBattTicks"},
  {9104, 2, RGULONG, "UsedDataBytes"},  
  
};

static const rgRegister _rgLoggedRecordTable[] ={
  {9600, 2, RGULONG, "num_log_recs"},
  {9602, 2, RGULONG, "log_rec_id"},
  {9604, 3, RGTIME, "rec_timestamp"},
  {9607, 2, RGFLOAT, "P1_press_measVal"},
  {9609, 1, RGUSHORT, "P1_press_DQID"},
  {96010, 2, RGFLOAT, "P2_temp_measVal"},
  {96012, 1, RGUSHORT, "P2_temp_DQID"},
  {96013, 2, RGFLOAT, "P3_level_measVal"},
  {96015, 1, RGUSHORT, "P3_level_DQID"},       
};

static const rgRegister _rgDeviceVoltageTable[] = {

  {109, 2, RGUSHORT, "int_voltage"},
  {110, 2, RGUSHORT, "ext_voltage"},
};

static const rgRegister _rgSensorCalibrationTable[] = {
    {100, 2, RGFLOAT, "Specific_Gravity" },
    {102, 2, RGFLOAT, "Poffset" },
    {104, 2, RGFLOAT, "Lref"},
    {106, 2, RGFLOAT, "Pref"},
};

The other problem is converting an array of uint16_t data to useful data types. I made the following union data types and the corresponding helper functions.

    union
    {
      uint16_t u[2];
      int i;
    } intData;

	union
    {
      uint16_t u[2];
      unsigned long ul;
    } ulongData;

    union
    {
      uint16_t u[2];
      float f;
    } floatData;

    union
    {
      uint16_t u[2];
      time_t t;
    } timeData;

    union
    {
      uint8_t u[64];
      char c[32];
    } stringData;



float _convertHEXtoFLOAT(uint16_t* data){

  for(int i=0; i<2; i++)
    floatData.u[1-i] = data[i];

  return floatData.f;

}

int _convertHEXtoINT(uint16_t* data){

		intData.u[0] = data[1];
		intData.u[1] = data[0];
		
		return intData.i;
}

String _convertHEXtoSTRING(uint16_t* data){

  String s;  

  for(int i=0; i<32; i++)
  {
    s.concat((char)data[i]);
  }
  s.trim();
  return s;
  
}



time_t _convertHEXtoTIME(uint16_t* data){
  // 3 register number
  // first 4 bytes represent time in seconds since 00:00:00 January 1, 1970 UTC
  
  for(int i=0; i < 3; i++)
      timeData.u[2-i] = data[i];

  return timeData.t;
}

Work in progress


#65

@rama what ever yo do for the improvement of the modbus library count with me for testing purposes.
now I will try once again the modbus master library that @peekay123 ported for photon, not sure why it didn’t work for me.


#66

I just made quick test with the modbus master library pkourany/ModbusMaster it gave me some error when compiling Modbus.ino
anyone knows if there is any other version that is OK?


#67

@luisgcu, try compiling with firmware 0.6.2-rc.1


#68

Thanks @peekay123 that solved the problem.


#69

Hello guys,
Did the photon have a similar way to cast number as arduino? Arduino Cast
I just test that on arduino at it work for me to convert the uint16_t data from modbus master to INT.
But I tried that on Photon but it didn’t work .
this is a sample code on arduino.

uint16_t var =65535;  // this represent  number = -1

void setup() {
  // put your setup code here, to run once:
Serial.begin(19200);
delay(2000);
int var2= (int)var;
Serial.print("Converted value from uint16_t to int: ");
Serial.println(var2);

}

void loop() {
  // put your main code here, to run repeatedly:

}



#70

That type cast is nothing specific to Arduino but it is standard C and hence supported as is.

Your trouble is that int on these 32bit processors is happily taking a 65535 as positive number as it can hold values between -2147483648 and +2147483647 :wink:
You may want to use int16_t (-32768…+32767) instead.


#71

thanks you @ScruffR I forgot that little detail that now I am playing with 32 bits processor… I have tested again declaring the variables as int16_t and it work perfect…
once again thanks.


#72

hello guys,
this is another mod-bus master library that i have tested with arduino and work fine.
I tried to compile for Photon i but i got errors in reference to the include "HardwareSerial.h"
I do’t have the enough skills to make the necessary change to get it working on photon.
appreciate if any of you can point me to the changes that are required to get it fully compatible with Particle photon.
Here is the link to download the full information about SimpleModbusMaster library. LINK

#include "SimpleModbusMaster.h"
#include "HardwareSerial.h"

// SimpleModbusMasterV2rev2

// state machine states
#define IDLE 1
#define WAITING_FOR_REPLY 2
#define WAITING_FOR_TURNAROUND 3

#define BUFFER_SIZE 64

unsigned char state;
unsigned char retry_count;
unsigned char TxEnablePin;

// frame[] is used to receive and transmit packages. 
// The maximum number of bytes in a modbus packet is 256 bytes
// This is limited to the serial buffer of 64 bytes
unsigned char frame[BUFFER_SIZE]; 
unsigned char buffer;
long timeout; // timeout interval
long polling; // turnaround delay interval
unsigned int T1_5; // inter character time out in microseconds
unsigned int frameDelay; // frame time out in microseconds
long delayStart; // init variable for turnaround and timeout delay
unsigned int total_no_of_packets; 
Packet* packetArray; // packet starting address
Packet* packet; // current packet
unsigned int* register_array; // pointer to masters register array
HardwareSerial* ModbusPort;

// function definitions
void idle();
void constructPacket();
unsigned char construct_F15();
unsigned char construct_F16();
void waiting_for_reply();
void processReply();
void waiting_for_turnaround();
void process_F1_F2();
void process_F3_F4();
void process_F5_F6_F15_F16();
void processError();
void processSuccess();
unsigned int calculateCRC(unsigned char bufferSize);
void sendPacket(unsigned char bufferSize);

// Modbus Master State Machine
void modbus_update() 
{
	switch (state)
	{
		case IDLE:
		idle();
		break;
		case WAITING_FOR_REPLY:
		waiting_for_reply();
		break;
		case WAITING_FOR_TURNAROUND:
		waiting_for_turnaround();
		break;
	}
}

void idle()
{
  static unsigned int packet_index;	
	
	unsigned int failed_connections = 0;
	
	unsigned char current_connection;
	
	do
	{		
		if (packet_index == total_no_of_packets) // wrap around to the beginning
			packet_index = 0;
				
		// proceed to the next packet
		packet = &packetArray[packet_index];
		
		// get the current connection status
		current_connection = packet->connection;
		
		if (!current_connection)
		{			
			// If all the connection attributes are false return
			// immediately to the main sketch
			if (++failed_connections == total_no_of_packets)
				return;
		}
		packet_index++;     
    
	// if a packet has no connection get the next one		
	}while (!current_connection); 
		
	constructPacket();
}
  
void constructPacket()
{	 
  packet->requests++;
  frame[0] = packet->id;
  frame[1] = packet->function;
  frame[2] = packet->address >> 8; // address Hi
  frame[3] = packet->address & 0xFF; // address Lo
	
	// For functions 1 & 2 data is the number of points
	// For function 5 data is either ON (0xFF00) or OFF (0x0000)
	// For function 6 data is exactly that, one register's data
  // For functions 3, 4 & 16 data is the number of registers
  // For function 15 data is the number of coils
	
	// The data attribute needs to be intercepted by F5 & F6 because these requests
	// include their data in the data register and not in the masters array
	if (packet->function == FORCE_SINGLE_COIL || packet->function == PRESET_SINGLE_REGISTER) 
		packet->data = register_array[packet->local_start_address]; // get the data
	
	
	frame[4] = packet->data >> 8; // MSB
	frame[5] = packet->data & 0xFF; // LSB
	
	unsigned char frameSize;    
	
  // construct the frame according to the modbus function  
  if (packet->function == PRESET_MULTIPLE_REGISTERS) 
		frameSize = construct_F16();
	else if (packet->function == FORCE_MULTIPLE_COILS)
		frameSize = construct_F15();
	else // else functions 1,2,3,4,5 & 6 is assumed. They all share the exact same request format.
    frameSize = 8; // the request is always 8 bytes in size for the above mentioned functions.
		
	unsigned int crc16 = calculateCRC(frameSize - 2);	
  frame[frameSize - 2] = crc16 >> 8; // split crc into 2 bytes
  frame[frameSize - 1] = crc16 & 0xFF;
  sendPacket(frameSize);

	state = WAITING_FOR_REPLY; // state change
	
	// if broadcast is requested (id == 0) for function 5,6,15 and 16 then override 
  // the previous state and force a success since the slave wont respond
	if (packet->id == 0)
			processSuccess();
}

unsigned char construct_F15()
{
	// function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2; 
	
  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad 
  if (packet->data % 16 > 0) 
  {
    no_of_registers++;
    no_of_bytes++;
  }
	
  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
	unsigned int temp;
	
  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data
    frame[index] = temp & 0xFF; 
    bytes_processed++;
     
    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
	unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes 
	return frameSize;
}

unsigned char construct_F16()
{
	unsigned char no_of_bytes = packet->data * 2; 
    
  // first 6 bytes of the array + no_of_bytes + 2 bytes CRC 
  frame[6] = no_of_bytes; // number of bytes
  unsigned char index = 7; // user data starts at index 7
	unsigned char no_of_registers = packet->data;
	unsigned int temp;
		
  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data
    frame[index] = temp >> 8;
    index++;
    frame[index] = temp & 0xFF;
    index++;
  }
	unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes 
	return frameSize;
}

void waiting_for_turnaround()
{
  if ((millis() - delayStart) > polling)
		state = IDLE;
}

// get the serial data from the buffer
void waiting_for_reply()
{
	if ((*ModbusPort).available()) // is there something to check?
	{
		unsigned char overflowFlag = 0;
		buffer = 0;
		while ((*ModbusPort).available())
		{
			// The maximum number of bytes is limited to the serial buffer size 
      // of BUFFER_SIZE. If more bytes is received than the BUFFER_SIZE the 
      // overflow flag will be set and the serial buffer will be read until
      // all the data is cleared from the receive buffer, while the slave is 
      // still responding.
			if (overflowFlag) 
				(*ModbusPort).read();
			else
			{
				if (buffer == BUFFER_SIZE)
					overflowFlag = 1;
			
				frame[buffer] = (*ModbusPort).read();
				buffer++;
			}
			// This is not 100% correct but it will suffice.
			// worst case scenario is if more than one character time expires
			// while reading from the buffer then the buffer is most likely empty
			// If there are more bytes after such a delay it is not supposed to
			// be received and thus will force a frame_error.
			delayMicroseconds(T1_5); // inter character time out
		}
			
		// The minimum buffer size from a slave can be an exception response of
    // 5 bytes. If the buffer was partially filled set a frame_error.
		// The maximum number of bytes in a modbus packet is 256 bytes.
		// The serial buffer limits this to 64 bytes.
	
		if ((buffer < 5) || overflowFlag)
			processError();       
      
		// Modbus over serial line datasheet states that if an unexpected slave 
    // responded the master must do nothing and continue with the time out.
		// This seems silly cause if an incorrect slave responded you would want to
    // have a quick turnaround and poll the right one again. If an unexpected 
    // slave responded it will most likely be a frame error in any event
		else if (frame[0] != packet->id) // check id returned
			processError();
		else
			processReply();
	}
	else if ((millis() - delayStart) > timeout) // check timeout
	{
		processError();
		state = IDLE; //state change, override processError() state
	}
}

void processReply()
{
	// combine the crc Low & High bytes
  unsigned int received_crc = ((frame[buffer - 2] << 8) | frame[buffer - 1]); 
  unsigned int calculated_crc = calculateCRC(buffer - 2);
	
	if (calculated_crc == received_crc) // verify checksum
	{
		// To indicate an exception response a slave will 'OR' 
		// the requested function with 0x80 
		if ((frame[1] & 0x80) == 0x80) // extract 0x80
		{
			packet->exception_errors++;
			processError();
		}
		else
		{
			switch (frame[1]) // check function returned
      {
        case READ_COIL_STATUS:
        case READ_INPUT_STATUS:
        process_F1_F2();
        break;
        case READ_INPUT_REGISTERS:
        case READ_HOLDING_REGISTERS:
        process_F3_F4();
        break;
				case FORCE_SINGLE_COIL:
				case PRESET_SINGLE_REGISTER:
        case FORCE_MULTIPLE_COILS:
        case PRESET_MULTIPLE_REGISTERS:
        process_F5_F6_F15_F16();
        break;
        default: // illegal function returned
        processError();
        break;
      }
		}
	} 
	else // checksum failed
	{
		processError();
	}
}

void process_F1_F2()
{
	// packet->data for function 1 & 2 is actually the number of boolean points
  unsigned char no_of_registers = packet->data / 16;
  unsigned char number_of_bytes = no_of_registers * 2; 
       
  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad 
  if (packet->data % 16 > 0) 
  {
    no_of_registers++;
    number_of_bytes++;
  }
             
  if (frame[2] == number_of_bytes) // check number of bytes returned
  { 
    unsigned char bytes_processed = 0;
    unsigned char index = 3; // start at the 4th element in the frame and combine the Lo byte  
    unsigned int temp;
    for (unsigned char i = 0; i < no_of_registers; i++)
    {
      temp = frame[index]; 
      bytes_processed++;
      if (bytes_processed < number_of_bytes)
      {
				temp = (frame[index + 1] << 8) | temp;
        bytes_processed++;
        index += 2;
      }
      register_array[packet->local_start_address + i] = temp;
    }
    processSuccess(); 
  }
  else // incorrect number of bytes returned 
    processError();
}

void process_F3_F4()
{
	// check number of bytes returned - unsigned int == 2 bytes
  // data for function 3 & 4 is the number of registers
  if (frame[2] == (packet->data * 2)) 
  {
    unsigned char index = 3;
    for (unsigned char i = 0; i < packet->data; i++)
    {
      // start at the 4th element in the frame and combine the Lo byte 
      register_array[packet->local_start_address + i] = (frame[index] << 8) | frame[index + 1]; 
      index += 2;
    }
    processSuccess(); 
  }
  else // incorrect number of bytes returned  
    processError();  
}

void process_F5_F6_F15_F16()
{
	// The repsonse of functions 5,6,15 & 16 are just an echo of the query
  unsigned int recieved_address = ((frame[2] << 8) | frame[3]);
  unsigned int recieved_data = ((frame[4] << 8) | frame[5]);
		
  if ((recieved_address == packet->address) && (recieved_data == packet->data))
    processSuccess();
  else
    processError();
}

void processError()
{
	packet->retries++;
	packet->failed_requests++;
	
	// if the number of retries have reached the max number of retries 
  // allowable, stop requesting the specific packet
  if (packet->retries == retry_count)
	{
    packet->connection = 0;
		packet->retries = 0;
	}
	state = WAITING_FOR_TURNAROUND;
	delayStart = millis(); // start the turnaround delay
}

void processSuccess()
{
	packet->successful_requests++; // transaction sent successfully
	packet->retries = 0; // if a request was successful reset the retry counter
	state = WAITING_FOR_TURNAROUND;
	delayStart = millis(); // start the turnaround delay
}
  
void modbus_configure(HardwareSerial* SerialPort,
											long baud,
											unsigned char byteFormat,
											long _timeout, 
											long _polling, 
											unsigned char _retry_count, 
											unsigned char _TxEnablePin, 
											Packet* _packets, 
											unsigned int _total_no_of_packets,
											unsigned int* _register_array)
{ 
	// Modbus states that a baud rate higher than 19200 must use a fixed 750 us 
  // for inter character time out and 1.75 ms for a frame delay for baud rates
  // below 19200 the timing is more critical and has to be calculated.
  // E.g. 9600 baud in a 11 bit packet is 9600/11 = 872 characters per second
  // In milliseconds this will be 872 characters per 1000ms. So for 1 character
  // 1000ms/872 characters is 1.14583ms per character and finally modbus states
  // an inter-character must be 1.5T or 1.5 times longer than a character. Thus
  // 1.5T = 1.14583ms * 1.5 = 1.71875ms. A frame delay is 3.5T.
	// Thus the formula is T1.5(us) = (1000ms * 1000(us) * 1.5 * 11bits)/baud
	// 1000ms * 1000(us) * 1.5 * 11bits = 16500000 can be calculated as a constant
	
	if (baud > 19200)
		T1_5 = 750; 
	else 
		T1_5 = 16500000/baud; // 1T * 1.5 = T1.5
		
	/* The modbus definition of a frame delay is a waiting period of 3.5 character times
		 between packets. This is not quite the same as the frameDelay implemented in
		 this library but does benifit from it.
		 The frameDelay variable is mainly used to ensure that the last character is 
		 transmitted without truncation. A value of 2 character times is chosen which
		 should suffice without holding the bus line high for too long.*/
		 
	frameDelay = T1_5 * 2; 
	
	// initialize
	state = IDLE;
  timeout = _timeout;
  polling = _polling;
	retry_count = _retry_count;
	TxEnablePin = _TxEnablePin;
	total_no_of_packets = _total_no_of_packets;
	packetArray = _packets;
	register_array = _register_array;
	
	ModbusPort = SerialPort;
	(*ModbusPort).begin(baud, byteFormat);
	
	pinMode(TxEnablePin, OUTPUT);
  digitalWrite(TxEnablePin, LOW);
	
} 

void modbus_construct(Packet *_packet, 
											unsigned char id, 
											unsigned char function, 
											unsigned int address, 
											unsigned int data,
											unsigned int local_start_address)
{
	_packet->id = id;
  _packet->function = function;
  _packet->address = address;
  _packet->data = data;
	_packet->local_start_address = local_start_address;
	_packet->connection = 1;
}

unsigned int calculateCRC(unsigned char bufferSize) 
{
  unsigned int temp, temp2, flag;
  temp = 0xFFFF;
  for (unsigned char i = 0; i < bufferSize; i++)
  {
    temp = temp ^ frame[i];
    for (unsigned char j = 1; j <= 8; j++)
    {
      flag = temp & 0x0001;
      temp >>= 1;
      if (flag)
        temp ^= 0xA001;
    }
  }
  // Reverse byte order. 
  temp2 = temp >> 8;
  temp = (temp << 8) | temp2;
  temp &= 0xFFFF;
  // the returned value is already swapped
  // crcLo byte is first & crcHi byte is last
  return temp; 
}

void sendPacket(unsigned char bufferSize)
{
	digitalWrite(TxEnablePin, HIGH);
		
	for (unsigned char i = 0; i < bufferSize; i++)
		(*ModbusPort).write(frame[i]);
		
	(*ModbusPort).flush();
	
	delayMicroseconds(frameDelay);
	
	digitalWrite(TxEnablePin, LOW);
		
	delayStart = millis(); // start the timeout delay	
}


#73

You could do this

#if defined(PARTICLE)
  #include <Serial2/Serial2.h>
  #include <Serial3/Serial3.h>
  #include <Serial4/Serial4.h>
  #include <Serial5/Serial5.h>
  USARTSerial* ModbusPort;
#else
  #include "HardwareSerial.h"
  HardwareSerial* ModbusPort;
#endif

But we can also ping @BDub to add some more Arduino compatibility defines for HardwareSerial for future releases.


#74

thanks you…


#75

Hello
for the very first time I am using the mod-bus library ( the one ported by @peekay123 ) to write a single holding register.
The problem that I have using it is with the function to writeSingleRegister it return OK at first call and the next fail and so on…
I tried different things… ( see commented lines) but none of those help to correct the problem.
My last try was to call 2 times the mod-bus write SR and that eventually worked… but I believe the problem can be solved in a different way.
thanks for any help.

void MBwriteSR () {
	uint8_t result2;
     
      // node.setTransmitBuffer(0, lowWord(0));
	//node.setTransmitBuffer(1, highWord(0));
	result2= node.writeSingleRegister(641,control_wrd);
	
	if (result2 == node.ku8MBSuccess)
  {
		 Particle.publish("Modbus Write OK");

	}
	else
	{
		 Particle.publish("Modbus Write FAIL");
	}
	node.clearResponseBuffer(); // if Timeout clearResponseBuffer and clearTransmitBuffer
	node.clearTransmitBuffer();
 //serialFlushInBuffer();
 result2= node.writeSingleRegister(641,control_wrd); // placing the modbus 2 time was my last test and worked getting rid of the systematic modbus write fail
}


#76

I am having some fun with Particle Photon modbus master + Voice control VFD drive and Amazon Echo dot ( Alexa).


#77

Hey @rama, thanks for the conversion part - among other things.

I’m a bit worried about the code for the time conversion: my modbus slave states date and time (enron log format) are each FP32, and consecutive, yet your code seems to deal with only the first 3 words and the timeData union is defined as 2 words only… where is the mistake? is the date/time one 64 bits number of secs since 1/1/70?

Cheers
phil


#78

Okay, just found the way date/time are coded according to the Enron Log format here: http://www.simplymodbus.ca/enron_history.htm

Specifically (example given on that page)
47EAF800: Date Stamp 32 bit float MMDDYY (120304.0 = Dec 3, 2004)
479C4000: Time Stamp 32 bit float HHMMSS (080000.0 = 8am)

So, 2 or 3 step conversion for either date or time:

  1. convert to float
  2. separate by hundreds -> MM DD YY or HH MM SS
  3. if required, convert then to time_t

#79

So I have tried to use the ModbusMaster library for some time with an electron, but I get a hardware fail (SOS + 1 blink) on the MBSerial.flush() statement when sending the request.

This is the electrical wiring:

I’ll add some of the code if necessary, but what could be the reason for the flush to fail that badly? something wrong in the firmware? a buffer overflow?..


#80

Nevermind. Doesn’t seem anyone is paying attention to this thread :slight_smile:

Anyway, Problem solved after many experimentations. Conclusion is, the library was not really working fine for me, for some reason I can’t explain. Got the latest version of the Arduino one on github (2.1.0) and ported it to the electron, using some of the “tricks” @peekay123 had written previously.

Got it working, built a Nuflo class that handles daily/hourly logs from a flow meter. All good. Code is not mine since it’s a freelance job, but I’ll be happy to help anyone having similar issues.