From ac851324f91e517c198fbc3dca4b12a4495c97ef Mon Sep 17 00:00:00 2001 From: rob040 Date: Mon, 20 Feb 2023 16:22:29 +0100 Subject: [PATCH 1/6] before doing any changes, we have to do some cleaning up by removing extraneous whitespace, without any code change. --- src/ModbusMaster.cpp | 193 ++++++++++++++++++------------------------- src/ModbusMaster.h | 114 ++++++++++++------------- 2 files changed, 134 insertions(+), 173 deletions(-) diff --git a/src/ModbusMaster.cpp b/src/ModbusMaster.cpp index 4169e58..7973c9a 100644 --- a/src/ModbusMaster.cpp +++ b/src/ModbusMaster.cpp @@ -29,10 +29,8 @@ Arduino library for communicating with Modbus slaves over RS232/485 (via RTU pro /* _____PROJECT INCLUDES_____________________________________________________ */ #include "ModbusMaster.h" - /* _____GLOBAL VARIABLES_____________________________________________________ */ - /* _____PUBLIC FUNCTIONS_____________________________________________________ */ /** Constructor. @@ -65,14 +63,13 @@ void ModbusMaster::begin(uint8_t slave, Stream &serial) _serial = &serial; _u8TransmitBufferIndex = 0; u16TransmitBufferLength = 0; - + #if __MODBUSMASTER_DEBUG__ pinMode(__MODBUSMASTER_DEBUG_PIN_A__, OUTPUT); pinMode(__MODBUSMASTER_DEBUG_PIN_B__, OUTPUT); #endif } - void ModbusMaster::beginTransmission(uint16_t u16Address) { _u16WriteAddress = u16Address; @@ -96,7 +93,6 @@ uint8_t ModbusMaster::requestFrom(uint16_t address, uint16_t quantity) return read; } - void ModbusMaster::sendBit(bool data) { uint8_t txBitIndex = u16TransmitBufferLength % 16; @@ -112,7 +108,6 @@ void ModbusMaster::sendBit(bool data) } } - void ModbusMaster::send(uint16_t data) { if (_u8TransmitBufferIndex < ku8MaxBufferSize) @@ -122,33 +117,22 @@ void ModbusMaster::send(uint16_t data) } } - void ModbusMaster::send(uint32_t data) { send(lowWord(data)); send(highWord(data)); } - void ModbusMaster::send(uint8_t data) { send(word(data)); } - - - - - - - - uint8_t ModbusMaster::available(void) { return _u8ResponseBufferLength - _u8ResponseBufferIndex; } - uint16_t ModbusMaster::receive(void) { if (_u8ResponseBufferIndex < _u8ResponseBufferLength) @@ -161,13 +145,6 @@ uint16_t ModbusMaster::receive(void) } } - - - - - - - /** Set idle time callback function (cooperative multitasking). @@ -216,7 +193,6 @@ void ModbusMaster::postTransmission(void (*postTransmission)()) _postTransmission = postTransmission; } - /** Retrieve data from response buffer. @@ -247,14 +223,13 @@ Clear Modbus response buffer. void ModbusMaster::clearResponseBuffer() { uint8_t i; - + for (i = 0; i < ku8MaxBufferSize; i++) { _u16ResponseBuffer[i] = 0; } } - /** Place data in transmit buffer. @@ -277,7 +252,6 @@ uint8_t ModbusMaster::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value) } } - /** Clear Modbus transmit buffer. @@ -287,7 +261,7 @@ Clear Modbus transmit buffer. void ModbusMaster::clearTransmitBuffer() { uint8_t i; - + for (i = 0; i < ku8MaxBufferSize; i++) { _u16TransmitBuffer[i] = 0; @@ -298,19 +272,19 @@ void ModbusMaster::clearTransmitBuffer() /** Modbus function 0x01 Read Coils. -This function code is used to read from 1 to 2000 contiguous status of -coils in a remote device. The request specifies the starting address, -i.e. the address of the first coil specified, and the number of coils. +This function code is used to read from 1 to 2000 contiguous status of +coils in a remote device. The request specifies the starting address, +i.e. the address of the first coil specified, and the number of coils. Coils are addressed starting at zero. -The coils in the response buffer are packed as one coil per bit of the -data field. Status is indicated as 1=ON and 0=OFF. The LSB of the first -data word contains the output addressed in the query. The other coils -follow toward the high order end of this word and from low order to high +The coils in the response buffer are packed as one coil per bit of the +data field. Status is indicated as 1=ON and 0=OFF. The LSB of the first +data word contains the output addressed in the query. The other coils +follow toward the high order end of this word and from low order to high order in subsequent words. -If the returned quantity is not a multiple of sixteen, the remaining -bits in the final data word will be padded with zeros (toward the high +If the returned quantity is not a multiple of sixteen, the remaining +bits in the final data word will be padded with zeros (toward the high order end of the word). @param u16ReadAddress address of first coil (0x0000..0xFFFF) @@ -325,23 +299,22 @@ uint8_t ModbusMaster::readCoils(uint16_t u16ReadAddress, uint16_t u16BitQty) return ModbusMasterTransaction(ku8MBReadCoils); } - /** Modbus function 0x02 Read Discrete Inputs. -This function code is used to read from 1 to 2000 contiguous status of -discrete inputs in a remote device. The request specifies the starting -address, i.e. the address of the first input specified, and the number +This function code is used to read from 1 to 2000 contiguous status of +discrete inputs in a remote device. The request specifies the starting +address, i.e. the address of the first input specified, and the number of inputs. Discrete inputs are addressed starting at zero. -The discrete inputs in the response buffer are packed as one input per -bit of the data field. Status is indicated as 1=ON; 0=OFF. The LSB of -the first data word contains the input addressed in the query. The other -inputs follow toward the high order end of this word, and from low order +The discrete inputs in the response buffer are packed as one input per +bit of the data field. Status is indicated as 1=ON; 0=OFF. The LSB of +the first data word contains the input addressed in the query. The other +inputs follow toward the high order end of this word, and from low order to high order in subsequent words. -If the returned quantity is not a multiple of sixteen, the remaining -bits in the final data word will be padded with zeros (toward the high +If the returned quantity is not a multiple of sixteen, the remaining +bits in the final data word will be padded with zeros (toward the high order end of the word). @param u16ReadAddress address of first discrete input (0x0000..0xFFFF) @@ -357,16 +330,15 @@ uint8_t ModbusMaster::readDiscreteInputs(uint16_t u16ReadAddress, return ModbusMasterTransaction(ku8MBReadDiscreteInputs); } - /** Modbus function 0x03 Read Holding Registers. -This function code is used to read the contents of a contiguous block of -holding registers in a remote device. The request specifies the starting -register address and the number of registers. Registers are addressed +This function code is used to read the contents of a contiguous block of +holding registers in a remote device. The request specifies the starting +register address and the number of registers. Registers are addressed starting at zero. -The register data in the response buffer is packed as one word per +The register data in the response buffer is packed as one word per register. @param u16ReadAddress address of the first holding register (0x0000..0xFFFF) @@ -382,16 +354,15 @@ uint8_t ModbusMaster::readHoldingRegisters(uint16_t u16ReadAddress, return ModbusMasterTransaction(ku8MBReadHoldingRegisters); } - /** Modbus function 0x04 Read Input Registers. -This function code is used to read from 1 to 125 contiguous input -registers in a remote device. The request specifies the starting -register address and the number of registers. Registers are addressed +This function code is used to read from 1 to 125 contiguous input +registers in a remote device. The request specifies the starting +register address and the number of registers. Registers are addressed starting at zero. -The register data in the response buffer is packed as one word per +The register data in the response buffer is packed as one word per register. @param u16ReadAddress address of the first input register (0x0000..0xFFFF) @@ -407,14 +378,13 @@ uint8_t ModbusMaster::readInputRegisters(uint16_t u16ReadAddress, return ModbusMasterTransaction(ku8MBReadInputRegisters); } - /** Modbus function 0x05 Write Single Coil. -This function code is used to write a single output to either ON or OFF -in a remote device. The requested ON/OFF state is specified by a -constant in the state field. A non-zero value requests the output to be -ON and a value of 0 requests it to be OFF. The request specifies the +This function code is used to write a single output to either ON or OFF +in a remote device. The requested ON/OFF state is specified by a +constant in the state field. A non-zero value requests the output to be +ON and a value of 0 requests it to be OFF. The request specifies the address of the coil to be forced. Coils are addressed starting at zero. @param u16WriteAddress address of the coil (0x0000..0xFFFF) @@ -429,12 +399,11 @@ uint8_t ModbusMaster::writeSingleCoil(uint16_t u16WriteAddress, uint8_t u8State) return ModbusMasterTransaction(ku8MBWriteSingleCoil); } - /** Modbus function 0x06 Write Single Register. -This function code is used to write a single holding register in a -remote device. The request specifies the address of the register to be +This function code is used to write a single holding register in a +remote device. The request specifies the address of the register to be written. Registers are addressed starting at zero. @param u16WriteAddress address of the holding register (0x0000..0xFFFF) @@ -451,16 +420,15 @@ uint8_t ModbusMaster::writeSingleRegister(uint16_t u16WriteAddress, return ModbusMasterTransaction(ku8MBWriteSingleRegister); } - /** Modbus function 0x0F Write Multiple Coils. -This function code is used to force each coil in a sequence of coils to -either ON or OFF in a remote device. The request specifies the coil +This function code is used to force each coil in a sequence of coils to +either ON or OFF in a remote device. The request specifies the coil references to be forced. Coils are addressed starting at zero. -The requested ON/OFF states are specified by contents of the transmit -buffer. A logical '1' in a bit position of the buffer requests the +The requested ON/OFF states are specified by contents of the transmit +buffer. A logical '1' in a bit position of the buffer requests the corresponding output to be ON. A logical '0' requests it to be OFF. @param u16WriteAddress address of the first coil (0x0000..0xFFFF) @@ -481,14 +449,13 @@ uint8_t ModbusMaster::writeMultipleCoils() return ModbusMasterTransaction(ku8MBWriteMultipleCoils); } - /** Modbus function 0x10 Write Multiple Registers. -This function code is used to write a block of contiguous registers (1 +This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device. -The requested written values are specified in the transmit buffer. Data +The requested written values are specified in the transmit buffer. Data is packed as one word per register. @param u16WriteAddress address of the holding register (0x0000..0xFFFF) @@ -511,17 +478,16 @@ uint8_t ModbusMaster::writeMultipleRegisters() return ModbusMasterTransaction(ku8MBWriteMultipleRegisters); } - /** Modbus function 0x16 Mask Write Register. -This function code is used to modify the contents of a specified holding -register using a combination of an AND mask, an OR mask, and the -register's current contents. The function can be used to set or clear +This function code is used to modify the contents of a specified holding +register using a combination of an AND mask, an OR mask, and the +register's current contents. The function can be used to set or clear individual bits in the register. -The request specifies the holding register to be written, the data to be -used as the AND mask, and the data to be used as the OR mask. Registers +The request specifies the holding register to be written, the data to be +used as the AND mask, and the data to be used as the OR mask. Registers are addressed starting at zero. The function's algorithm is: @@ -543,18 +509,17 @@ uint8_t ModbusMaster::maskWriteRegister(uint16_t u16WriteAddress, return ModbusMasterTransaction(ku8MBMaskWriteRegister); } - /** Modbus function 0x17 Read Write Multiple Registers. -This function code performs a combination of one read operation and one -write operation in a single MODBUS transaction. The write operation is -performed before the read. Holding registers are addressed starting at +This function code performs a combination of one read operation and one +write operation in a single MODBUS transaction. The write operation is +performed before the read. Holding registers are addressed starting at zero. -The request specifies the starting address and number of holding -registers to be read as well as the starting address, and the number of -holding registers. The data to be written is specified in the transmit +The request specifies the starting address and number of holding +registers to be read as well as the starting address, and the number of +holding registers. The data to be written is specified in the transmit buffer. @param u16ReadAddress address of the first holding register (0x0000..0xFFFF) @@ -606,11 +571,11 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) uint32_t u32StartTime; uint8_t u8BytesLeft = 8; uint8_t u8MBStatus = ku8MBSuccess; - + // assemble Modbus Request Application Data Unit u8ModbusADU[u8ModbusADUSize++] = _u8MBSlave; u8ModbusADU[u8ModbusADUSize++] = u8MBFunction; - + switch(u8MBFunction) { case ku8MBReadCoils: @@ -624,7 +589,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadQty); break; } - + switch(u8MBFunction) { case ku8MBWriteSingleCoil: @@ -637,19 +602,19 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteAddress); break; } - + switch(u8MBFunction) { case ku8MBWriteSingleCoil: u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty); break; - + case ku8MBWriteSingleRegister: u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[0]); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[0]); break; - + case ku8MBWriteMultipleCoils: u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty); @@ -662,27 +627,27 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) case 0: // i is even u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[i >> 1]); break; - + case 1: // i is odd u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[i >> 1]); break; } } break; - + case ku8MBWriteMultipleRegisters: case ku8MBReadWriteMultipleRegisters: u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty << 1); - + for (i = 0; i < lowByte(_u16WriteQty); i++) { u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[i]); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[i]); } break; - + case ku8MBMaskWriteRegister: u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[0]); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[0]); @@ -690,7 +655,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[1]); break; } - + // append CRC u16CRC = 0xFFFF; for (i = 0; i < u8ModbusADUSize; i++) @@ -713,14 +678,14 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) { _serial->write(u8ModbusADU[i]); } - + u8ModbusADUSize = 0; _serial->flush(); // flush transmit buffer if (_postTransmission) { _postTransmission(); } - + // loop until we run out of time or bytes, or an error occurs u32StartTime = millis(); while (u8BytesLeft && !u8MBStatus) @@ -749,7 +714,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) digitalWrite(__MODBUSMASTER_DEBUG_PIN_B__, false); #endif } - + // evaluate slave ID, function code once enough bytes have been read if (u8ModbusADUSize == 5) { @@ -759,21 +724,21 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8MBStatus = ku8MBInvalidSlaveID; break; } - + // verify response is for correct Modbus function code (mask exception bit 7) if ((u8ModbusADU[1] & 0x7F) != u8MBFunction) { u8MBStatus = ku8MBInvalidFunction; break; } - + // check whether Modbus exception occurred; return Modbus Exception Code if (bitRead(u8ModbusADU[1], 7)) { u8MBStatus = u8ModbusADU[2]; break; } - + // evaluate returned Modbus function code switch(u8ModbusADU[1]) { @@ -784,14 +749,14 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) case ku8MBReadWriteMultipleRegisters: u8BytesLeft = u8ModbusADU[2]; break; - + case ku8MBWriteSingleCoil: case ku8MBWriteMultipleCoils: case ku8MBWriteSingleRegister: case ku8MBWriteMultipleRegisters: u8BytesLeft = 3; break; - + case ku8MBMaskWriteRegister: u8BytesLeft = 5; break; @@ -802,7 +767,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8MBStatus = ku8MBResponseTimedOut; } } - + // verify response is large enough to inspect further if (!u8MBStatus && u8ModbusADUSize >= 5) { @@ -812,7 +777,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) { u16CRC = crc16_update(u16CRC, u8ModbusADU[i]); } - + // verify CRC if (!u8MBStatus && (lowByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 2] || highByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 1])) @@ -836,10 +801,10 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) { _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 4], u8ModbusADU[2 * i + 3]); } - + _u8ResponseBufferLength = i; } - + // in the event of an odd number of bytes, load last byte into zero-padded word if (u8ModbusADU[2] % 2) { @@ -847,11 +812,11 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) { _u16ResponseBuffer[i] = word(0, u8ModbusADU[2 * i + 3]); } - + _u8ResponseBufferLength = i + 1; } break; - + case ku8MBReadInputRegisters: case ku8MBReadHoldingRegisters: case ku8MBReadWriteMultipleRegisters: @@ -862,13 +827,13 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) { _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 3], u8ModbusADU[2 * i + 4]); } - + _u8ResponseBufferLength = i; } break; } } - + _u8TransmitBufferIndex = 0; u16TransmitBufferLength = 0; _u8ResponseBufferIndex = 0; diff --git a/src/ModbusMaster.h b/src/ModbusMaster.h index 8c433e6..8d1b9ac 100644 --- a/src/ModbusMaster.h +++ b/src/ModbusMaster.h @@ -31,11 +31,9 @@ Arduino library for communicating with Modbus slaves over RS232/485 (via RTU pro */ - #ifndef ModbusMaster_h #define ModbusMaster_h - /** @def __MODBUSMASTER_DEBUG__ (0) Set to 1 to enable debugging features within class: @@ -52,7 +50,6 @@ Set to 1 to enable debugging features within class: /* _____UTILITY MACROS_______________________________________________________ */ - /* _____PROJECT INCLUDES_____________________________________________________ */ // functions to calculate Modbus Application Data Unit CRC #include "util/crc16.h" @@ -63,14 +60,14 @@ Set to 1 to enable debugging features within class: /* _____CLASS DEFINITIONS____________________________________________________ */ /** -Arduino class library for communicating with Modbus slaves over +Arduino class library for communicating with Modbus slaves over RS232/485 (via RTU protocol). */ class ModbusMaster { public: ModbusMaster(); - + void begin(uint8_t, Stream &serial); void idle(void (*)()); void preTransmission(void (*)()); @@ -79,59 +76,59 @@ class ModbusMaster // Modbus exception codes /** Modbus protocol illegal function exception. - + The function code received in the query is not an allowable action for the server (or slave). This may be because the function code is only applicable to newer devices, and was not implemented in the unit selected. It could also indicate that the server (or slave) is in the wrong state to process a request of this type, for example because it is unconfigured and is being asked to return register values. - + @ingroup constant */ static const uint8_t ku8MBIllegalFunction = 0x01; /** Modbus protocol illegal data address exception. - - The data address received in the query is not an allowable address for - the server (or slave). More specifically, the combination of reference - number and transfer length is invalid. For a controller with 100 - registers, the ADU addresses the first register as 0, and the last one - as 99. If a request is submitted with a starting register address of 96 - and a quantity of registers of 4, then this request will successfully - operate (address-wise at least) on registers 96, 97, 98, 99. If a - request is submitted with a starting register address of 96 and a - quantity of registers of 5, then this request will fail with Exception - Code 0x02 "Illegal Data Address" since it attempts to operate on - registers 96, 97, 98, 99 and 100, and there is no register with address - 100. - + + The data address received in the query is not an allowable address for + the server (or slave). More specifically, the combination of reference + number and transfer length is invalid. For a controller with 100 + registers, the ADU addresses the first register as 0, and the last one + as 99. If a request is submitted with a starting register address of 96 + and a quantity of registers of 4, then this request will successfully + operate (address-wise at least) on registers 96, 97, 98, 99. If a + request is submitted with a starting register address of 96 and a + quantity of registers of 5, then this request will fail with Exception + Code 0x02 "Illegal Data Address" since it attempts to operate on + registers 96, 97, 98, 99 and 100, and there is no register with address + 100. + @ingroup constant */ static const uint8_t ku8MBIllegalDataAddress = 0x02; - + /** Modbus protocol illegal data value exception. - - A value contained in the query data field is not an allowable value for - server (or slave). This indicates a fault in the structure of the - remainder of a complex request, such as that the implied length is - incorrect. It specifically does NOT mean that a data item submitted for - storage in a register has a value outside the expectation of the - application program, since the MODBUS protocol is unaware of the + + A value contained in the query data field is not an allowable value for + server (or slave). This indicates a fault in the structure of the + remainder of a complex request, such as that the implied length is + incorrect. It specifically does NOT mean that a data item submitted for + storage in a register has a value outside the expectation of the + application program, since the MODBUS protocol is unaware of the significance of any particular value of any particular register. - + @ingroup constant */ static const uint8_t ku8MBIllegalDataValue = 0x03; - + /** Modbus protocol slave device failure exception. - + An unrecoverable error occurred while the server (or slave) was attempting to perform the requested action. - + @ingroup constant */ static const uint8_t ku8MBSlaveDeviceFailure = 0x04; @@ -139,60 +136,60 @@ class ModbusMaster // Class-defined success/exception codes /** ModbusMaster success. - + Modbus transaction was successful; the following checks were valid: - slave ID - function code - response code - data - CRC - + @ingroup constant */ static const uint8_t ku8MBSuccess = 0x00; - + /** ModbusMaster invalid response slave ID exception. - + The slave ID in the response does not match that of the request. - + @ingroup constant */ static const uint8_t ku8MBInvalidSlaveID = 0xE0; - + /** ModbusMaster invalid response function exception. - + The function code in the response does not match that of the request. - + @ingroup constant */ static const uint8_t ku8MBInvalidFunction = 0xE1; - + /** ModbusMaster response timed out exception. - - The entire response was not received within the timeout period, - ModbusMaster::ku8MBResponseTimeout. - + + The entire response was not received within the timeout period, + ModbusMaster::ku8MBResponseTimeout. + @ingroup constant */ static const uint8_t ku8MBResponseTimedOut = 0xE2; - + /** ModbusMaster invalid response CRC exception. - + The CRC in the response does not match the one calculated. - + @ingroup constant */ static const uint8_t ku8MBInvalidCRC = 0xE3; - + uint16_t getResponseBuffer(uint8_t); void clearResponseBuffer(); uint8_t setTransmitBuffer(uint8_t, uint16_t); void clearTransmitBuffer(); - + void beginTransmission(uint16_t); uint8_t requestFrom(uint16_t, uint16_t); void sendBit(bool); @@ -201,8 +198,7 @@ class ModbusMaster void send(uint32_t); uint8_t available(void); uint16_t receive(void); - - + uint8_t readCoils(uint16_t, uint16_t); uint8_t readDiscreteInputs(uint16_t, uint16_t); uint8_t readHoldingRegisters(uint16_t, uint16_t); @@ -216,11 +212,11 @@ class ModbusMaster uint8_t maskWriteRegister(uint16_t, uint16_t, uint16_t); uint8_t readWriteMultipleRegisters(uint16_t, uint16_t, uint16_t, uint16_t); uint8_t readWriteMultipleRegisters(uint16_t, uint16_t); - + private: Stream* _serial; ///< reference to serial port object uint8_t _u8MBSlave; ///< Modbus slave (1..255) initialized in begin() - static const uint8_t ku8MaxBufferSize = 64; ///< size of response/transmit buffers + static const uint8_t ku8MaxBufferSize = 64; ///< size of response/transmit buffers uint16_t _u16ReadAddress; ///< slave register from which to read uint16_t _u16ReadQty; ///< quantity of words to read uint16_t _u16ResponseBuffer[ku8MaxBufferSize]; ///< buffer to store Modbus slave response; read via GetResponseBuffer() @@ -233,7 +229,7 @@ class ModbusMaster uint16_t* rxBuffer; // from Wire.h -- need to clean this up Rx uint8_t _u8ResponseBufferIndex; uint8_t _u8ResponseBufferLength; - + // Modbus function codes for bit access static const uint8_t ku8MBReadCoils = 0x01; ///< Modbus function 0x01 Read Coils static const uint8_t ku8MBReadDiscreteInputs = 0x02; ///< Modbus function 0x02 Read Discrete Inputs @@ -247,13 +243,13 @@ class ModbusMaster static const uint8_t ku8MBWriteMultipleRegisters = 0x10; ///< Modbus function 0x10 Write Multiple Registers static const uint8_t ku8MBMaskWriteRegister = 0x16; ///< Modbus function 0x16 Mask Write Register static const uint8_t ku8MBReadWriteMultipleRegisters = 0x17; ///< Modbus function 0x17 Read Write Multiple Registers - + // Modbus timeout [milliseconds] static const uint16_t ku16MBResponseTimeout = 2000; ///< Modbus timeout [milliseconds] - + // master function that conducts Modbus transactions uint8_t ModbusMasterTransaction(uint8_t u8MBFunction); - + // idle callback function; gets called during idle time between TX and RX void (*_idle)(); // preTransmission callback function; gets called before writing a Modbus message From ec536ecc94df1424a75bca62c1727a9da379ef7b Mon Sep 17 00:00:00 2001 From: rob040 Date: Mon, 20 Feb 2023 17:48:22 +0100 Subject: [PATCH 2/6] Comment out unused/unwanted public function requestFrom(); it was already marked to be eliminated, and its implementation was flawed. Comment out unneeded private members txBuffer, rxBuffer. Name the public member arguments; do not let the user guess which argument is what. Also do not require the user to consult the documentation. Include the small inline functions into ModbusMaster.h; this also eliminates the compilation warning about defined but unused crc16_update(). --- src/ModbusMaster.cpp | 35 +++++++------- src/ModbusMaster.h | 110 ++++++++++++++++++++++++++++++------------- 2 files changed, 96 insertions(+), 49 deletions(-) diff --git a/src/ModbusMaster.cpp b/src/ModbusMaster.cpp index 7973c9a..776aefc 100644 --- a/src/ModbusMaster.cpp +++ b/src/ModbusMaster.cpp @@ -24,7 +24,9 @@ Arduino library for communicating with Modbus slaves over RS232/485 (via RTU pro limitations under the License. */ - +//uncomment for DEBUG +//#define DEBUG_SEND_MESSAGE +//#define DEBUG_RECEIVED_MESSAGE /* _____PROJECT INCLUDES_____________________________________________________ */ #include "ModbusMaster.h" @@ -58,7 +60,6 @@ Call once class has been instantiated, typically within setup(). */ void ModbusMaster::begin(uint8_t slave, Stream &serial) { -// txBuffer = (uint16_t*) calloc(ku8MaxBufferSize, sizeof(uint16_t)); _u8MBSlave = slave; _serial = &serial; _u8TransmitBufferIndex = 0; @@ -78,20 +79,20 @@ void ModbusMaster::beginTransmission(uint16_t u16Address) } // eliminate this function in favor of using existing MB request functions -uint8_t ModbusMaster::requestFrom(uint16_t address, uint16_t quantity) -{ - uint8_t read; - // clamp to buffer length - if (quantity > ku8MaxBufferSize) - { - quantity = ku8MaxBufferSize; - } - // set rx buffer iterator vars - _u8ResponseBufferIndex = 0; - _u8ResponseBufferLength = read; - - return read; -} +//uint8_t ModbusMaster::requestFrom(uint16_t address, uint16_t quantity) +//{ +// uint8_t read; +// // clamp to buffer length +// if (quantity > ku8MaxBufferSize) +// { +// quantity = ku8MaxBufferSize; +// } +// // set rx buffer iterator vars +// _u8ResponseBufferIndex = 0; +// _u8ResponseBufferLength = read; +// +// return read; +//} void ModbusMaster::sendBit(bool data) { @@ -371,7 +372,7 @@ register. @ingroup register */ uint8_t ModbusMaster::readInputRegisters(uint16_t u16ReadAddress, - uint8_t u16ReadQty) + uint16_t u16ReadQty) { _u16ReadAddress = u16ReadAddress; _u16ReadQty = u16ReadQty; diff --git a/src/ModbusMaster.h b/src/ModbusMaster.h index 8d1b9ac..83d279f 100644 --- a/src/ModbusMaster.h +++ b/src/ModbusMaster.h @@ -52,11 +52,57 @@ Set to 1 to enable debugging features within class: /* _____PROJECT INCLUDES_____________________________________________________ */ // functions to calculate Modbus Application Data Unit CRC -#include "util/crc16.h" +//#include "crc16.h" +/** @ingroup util_crc16 + Processor-independent CRC-16 calculation. + + Polynomial: x^16 + x^15 + x^2 + 1 (0xA001)
+ Initial value: 0xFFFF + + This CRC is normally used in disk-drive controllers. + + @param uint16_t crc (0x0000..0xFFFF) + @param uint8_t a (0x00..0xFF) + @return calculated CRC (0x0000..0xFFFF) +*/ +inline uint16_t crc16_update(uint16_t crc, uint8_t a) +{ + int i; + + crc ^= a; + for (i = 0; i < 8; ++i) + { + if (crc & 1) + crc = (crc >> 1) ^ 0xA001; + else + crc = (crc >> 1); + } + return crc; +} // functions to manipulate words -#include "util/word.h" +//#include "word.h" +/** @ingroup util_word + Return low word of a 32-bit integer. + @param uint32_t ww (0x00000000..0xFFFFFFFF) + @return low word of input (0x0000..0xFFFF) +*/ +static inline uint16_t lowWord(uint32_t ww) +{ + return (uint16_t)((ww)&0xFFFF); +} + +/** @ingroup util_word + Return high word of a 32-bit integer. + + @param uint32_t ww (0x00000000..0xFFFFFFFF) + @return high word of input (0x0000..0xFFFF) +*/ +static inline uint16_t highWord(uint32_t ww) +{ + return (uint16_t)((ww) >> 16); +} /* _____CLASS DEFINITIONS____________________________________________________ */ /** @@ -68,10 +114,10 @@ class ModbusMaster public: ModbusMaster(); - void begin(uint8_t, Stream &serial); - void idle(void (*)()); - void preTransmission(void (*)()); - void postTransmission(void (*)()); + void begin(uint8_t slaveId, Stream &serial); + void idle(void (*idleCallbackFn)()); + void preTransmission(void (*preTxCallbackFn)()); + void postTransmission(void (*postTxCallbackFn)()); // Modbus exception codes /** @@ -185,33 +231,33 @@ class ModbusMaster */ static const uint8_t ku8MBInvalidCRC = 0xE3; - uint16_t getResponseBuffer(uint8_t); - void clearResponseBuffer(); - uint8_t setTransmitBuffer(uint8_t, uint16_t); - void clearTransmitBuffer(); - - void beginTransmission(uint16_t); - uint8_t requestFrom(uint16_t, uint16_t); - void sendBit(bool); - void send(uint8_t); - void send(uint16_t); - void send(uint32_t); + uint16_t getResponseBuffer(uint8_t Index); + void clearResponseBuffer(void); + uint8_t setTransmitBuffer(uint8_t Offset, uint16_t Value); + void clearTransmitBuffer(void); + + void beginTransmission(uint16_t u16Address); + //uint8_t requestFrom(uint16_t Addr, uint16_t Qty); + void sendBit(bool data); + void send(uint8_t data); + void send(uint16_t data); + void send(uint32_t data); uint8_t available(void); uint16_t receive(void); - uint8_t readCoils(uint16_t, uint16_t); - uint8_t readDiscreteInputs(uint16_t, uint16_t); - uint8_t readHoldingRegisters(uint16_t, uint16_t); - uint8_t readInputRegisters(uint16_t, uint8_t); - uint8_t writeSingleCoil(uint16_t, uint8_t); - uint8_t writeSingleRegister(uint16_t, uint16_t); - uint8_t writeMultipleCoils(uint16_t, uint16_t); - uint8_t writeMultipleCoils(); - uint8_t writeMultipleRegisters(uint16_t, uint16_t); - uint8_t writeMultipleRegisters(); - uint8_t maskWriteRegister(uint16_t, uint16_t, uint16_t); - uint8_t readWriteMultipleRegisters(uint16_t, uint16_t, uint16_t, uint16_t); - uint8_t readWriteMultipleRegisters(uint16_t, uint16_t); + uint8_t readCoils(uint16_t Addr, uint16_t Qty); + uint8_t readDiscreteInputs(uint16_t Addr, uint16_t Qty); + uint8_t readHoldingRegisters(uint16_t Addr, uint16_t Qty); + uint8_t readInputRegisters(uint16_t Addr, uint16_t Qty); + uint8_t writeSingleCoil(uint16_t Addr, uint8_t State); + uint8_t writeSingleRegister(uint16_t Addr, uint16_t Value); + uint8_t writeMultipleCoils(uint16_t Addr, uint16_t Qty); + uint8_t writeMultipleCoils(void); + uint8_t writeMultipleRegisters(uint16_t Addr, uint16_t Qty); + uint8_t writeMultipleRegisters(void); + uint8_t maskWriteRegister(uint16_t u16WriteAddress, uint16_t u16AndMask, uint16_t u16OrMask); + uint8_t readWriteMultipleRegisters(uint16_t u16ReadAddress, uint16_t u16ReadQty, uint16_t u16WriteAddress, uint16_t u16WriteQty); + uint8_t readWriteMultipleRegisters(uint16_t Addr, uint16_t Qty); private: Stream* _serial; ///< reference to serial port object @@ -223,10 +269,10 @@ class ModbusMaster uint16_t _u16WriteAddress; ///< slave register to which to write uint16_t _u16WriteQty; ///< quantity of words to write uint16_t _u16TransmitBuffer[ku8MaxBufferSize]; ///< buffer containing data to transmit to Modbus slave; set via SetTransmitBuffer() - uint16_t* txBuffer; // from Wire.h -- need to clean this up Rx + //uint16_t* txBuffer; // from Wire.h -- need to clean this up Rx uint8_t _u8TransmitBufferIndex; uint16_t u16TransmitBufferLength; - uint16_t* rxBuffer; // from Wire.h -- need to clean this up Rx + //uint16_t* rxBuffer; // from Wire.h -- need to clean this up Rx uint8_t _u8ResponseBufferIndex; uint8_t _u8ResponseBufferLength; From 19f2700efe2f5258b2dbe285a214f5ee0006477e Mon Sep 17 00:00:00 2001 From: rob040 Date: Mon, 20 Feb 2023 18:21:17 +0100 Subject: [PATCH 3/6] Remove commented-out functions. Add Debug option, to allow to see what actually is send and received, and if some rubbish is received between transmit and receive, which would point to hardware related issues. --- src/ModbusMaster.cpp | 80 ++++++++++++++++++++++++++++++++++---------- src/ModbusMaster.h | 2 -- 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/src/ModbusMaster.cpp b/src/ModbusMaster.cpp index 776aefc..d17eef4 100644 --- a/src/ModbusMaster.cpp +++ b/src/ModbusMaster.cpp @@ -27,6 +27,7 @@ Arduino library for communicating with Modbus slaves over RS232/485 (via RTU pro //uncomment for DEBUG //#define DEBUG_SEND_MESSAGE //#define DEBUG_RECEIVED_MESSAGE +//#define DebugSerial Serial /* _____PROJECT INCLUDES_____________________________________________________ */ #include "ModbusMaster.h" @@ -78,22 +79,6 @@ void ModbusMaster::beginTransmission(uint16_t u16Address) u16TransmitBufferLength = 0; } -// eliminate this function in favor of using existing MB request functions -//uint8_t ModbusMaster::requestFrom(uint16_t address, uint16_t quantity) -//{ -// uint8_t read; -// // clamp to buffer length -// if (quantity > ku8MaxBufferSize) -// { -// quantity = ku8MaxBufferSize; -// } -// // set rx buffer iterator vars -// _u8ResponseBufferIndex = 0; -// _u8ResponseBufferLength = read; -// -// return read; -//} - void ModbusMaster::sendBit(bool data) { uint8_t txBitIndex = u16TransmitBufferLength % 16; @@ -667,9 +652,37 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = highByte(u16CRC); u8ModbusADU[u8ModbusADUSize] = 0; + //DEBUG:dump TX message +#ifdef DEBUG_SEND_MESSAGE + if (_serial->available()) + { + DebugSerial.print(F("\nFlushRd: ")); // flush receive buffer before transmitting request - while (_serial->read() != -1); + do + { + int rc = _serial->read(); + if (rc == -1) break; + i = rc; + if (i < 0x10) DebugSerial.print('0'); + DebugSerial.print((uint8_t)i, HEX); + DebugSerial.print(' '); + } while (1); + DebugSerial.println(); + } + DebugSerial.print(F("Sending: ")); + for (i = 0; i < u8ModbusADUSize; i++) + { + if (u8ModbusADU[i] < 0x10) DebugSerial.print('0'); + DebugSerial.print(u8ModbusADU[i], HEX); + DebugSerial.print(' '); + } + DebugSerial.println(); +#else + // flush receive buffer before transmitting request + while (_serial->read() != -1) + ; +#endif // transmit request if (_preTransmission) { @@ -768,6 +781,39 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8MBStatus = ku8MBResponseTimedOut; } } + //DEBUG:dump RX message +#ifdef DEBUG_RECEIVED_MESSAGE + DebugSerial.print("Received: "); + for (i = 0; i < u8ModbusADUSize; i++) + { + if (u8ModbusADU[i] < 0x10) DebugSerial.print('0'); + DebugSerial.print(u8ModbusADU[i], HEX); + DebugSerial.print(' '); + } + DebugSerial.println(); + bool blprintstr = false; + i = (u8ModbusADU[1] == ku8MBReadDeviceIdentifiers) ? 10 : 3; + for (; i < u8ModbusADUSize; i++) + { + if ((u8ModbusADU[i] >= ' ') && (u8ModbusADU[i] <= 'z')) + { + if (!blprintstr) + { + blprintstr = true; + DebugSerial.print(" \""); + } + DebugSerial.print((char)u8ModbusADU[i]); + } + else if (blprintstr) + { + blprintstr = false; + DebugSerial.print("\","); + } + } + DebugSerial.println(); + DebugSerial.print("Status:"); + DebugSerial.println(u8MBStatus, HEX); +#endif // verify response is large enough to inspect further if (!u8MBStatus && u8ModbusADUSize >= 5) diff --git a/src/ModbusMaster.h b/src/ModbusMaster.h index 83d279f..e2cf017 100644 --- a/src/ModbusMaster.h +++ b/src/ModbusMaster.h @@ -269,10 +269,8 @@ class ModbusMaster uint16_t _u16WriteAddress; ///< slave register to which to write uint16_t _u16WriteQty; ///< quantity of words to write uint16_t _u16TransmitBuffer[ku8MaxBufferSize]; ///< buffer containing data to transmit to Modbus slave; set via SetTransmitBuffer() - //uint16_t* txBuffer; // from Wire.h -- need to clean this up Rx uint8_t _u8TransmitBufferIndex; uint16_t u16TransmitBufferLength; - //uint16_t* rxBuffer; // from Wire.h -- need to clean this up Rx uint8_t _u8ResponseBufferIndex; uint8_t _u8ResponseBufferLength; From 3ef6b4482f7a3b001b9b8dd8b9c17cd299c5de78 Mon Sep 17 00:00:00 2001 From: rob040 Date: Mon, 20 Feb 2023 18:42:00 +0100 Subject: [PATCH 4/6] Add method to change/request (get/set) the SlaveID. Add method to change/request (get/set) the ResponseTimeout. Add method to request the response size of data in the response buffer. Add Modbus function 0x2B/0E Read DeviceIdentifiers ku8MBReadDeviceIdentifiers. --- src/ModbusMaster.cpp | 116 ++++++++++++++++++++++++++++++++++++++++++- src/ModbusMaster.h | 15 +++++- 2 files changed, 128 insertions(+), 3 deletions(-) diff --git a/src/ModbusMaster.cpp b/src/ModbusMaster.cpp index d17eef4..12516da 100644 --- a/src/ModbusMaster.cpp +++ b/src/ModbusMaster.cpp @@ -47,6 +47,7 @@ ModbusMaster::ModbusMaster(void) _idle = 0; _preTransmission = 0; _postTransmission = 0; + _u16ResponseTimeout = ku16MBDefaultResponseTimeout; } /** @@ -183,6 +184,7 @@ void ModbusMaster::postTransmission(void (*postTransmission)()) Retrieve data from response buffer. @see ModbusMaster::clearResponseBuffer() +@see ModbusMaster::getResponseSize() @param u8Index index of response buffer array (0x00..0x3F) @return value in position u8Index of response buffer (0x0000..0xFFFF) @ingroup buffer @@ -199,6 +201,17 @@ uint16_t ModbusMaster::getResponseBuffer(uint8_t u8Index) } } +/** +Get number of words in response buffer. + +@see ModbusMaster::getResponseBuffer +@return value in position u8Index of response buffer (0x0000..0xFFFF) +@ingroup buffer + */ +uint8_t ModbusMaster::getResponseSize() +{ + return _u8ResponseBufferLength; +} /** Clear Modbus response buffer. @@ -254,6 +267,41 @@ void ModbusMaster::clearTransmitBuffer() } } +/** + * Set Modbus save id + * Change the slave id that is set with begin method. + * */ +void ModbusMaster::setSlaveId(uint8_t slaveid) +{ + _u8MBSlave = slaveid; +} + +/** + * Get Modbus save id + * */ +uint8_t ModbusMaster::getSlaveId(void) +{ + return _u8MBSlave; +} + + +/** +Get the response timeout. Value is in ms. +*/ +uint16_t ModbusMaster::getResponseTimeout() +{ + return _u16ResponseTimeout; +} + +/** +Sets the response timeout. Value should be given in ms. +The default is 2000 ms. +*/ +void ModbusMaster::setResponseTimeout(uint16_t timeout) +{ + _u16ResponseTimeout = timeout; +} + /** Modbus function 0x01 Read Coils. @@ -533,6 +581,18 @@ uint8_t ModbusMaster::readWriteMultipleRegisters(uint16_t u16ReadAddress, return ModbusMasterTransaction(ku8MBReadWriteMultipleRegisters); } +/* + * ku8MBReadDeviceIdentifiers = 0x2B/0E + */ +//uint8_t ModbusMaster::readDeviceIdentifiers(uint8_t ObjectId) +uint8_t ModbusMaster::readDeviceIdentifiers(uint8_t ReadId, uint8_t ObjectId, char *pu8ReadStrBuffer, uint8_t u8ReadStrBufferMaxSize, uint8_t *pu8ReadStrSize) +{ + _u16ReadAddress = ((uint16_t)ReadId << 8) | ObjectId; + _pu8ReadStrBuffer = pu8ReadStrBuffer; + _u8ReadStrBufferMaxSize = u8ReadStrBufferMaxSize; + _pu8ReadStrSize = pu8ReadStrSize; + return ModbusMasterTransaction(ku8MBReadDeviceIdentifiers); +} /* _____PRIVATE FUNCTIONS____________________________________________________ */ /** @@ -553,6 +613,8 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) uint8_t u8ModbusADU[256]; uint8_t u8ModbusADUSize = 0; uint8_t i, u8Qty; + uint8_t u8RDIobjcnt = 0; + uint8_t u8RDInextObjSzIdx = 255; uint16_t u16CRC; uint32_t u32StartTime; uint8_t u8BytesLeft = 8; @@ -574,6 +636,14 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadQty); u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadQty); break; + case ku8MBReadDeviceIdentifiers: + //u8ModbusADUSize = 0; + //u8ModbusADU[u8ModbusADUSize++] = u8MBFunction; + u8ModbusADU[u8ModbusADUSize++] = 0x0E; // MEI type + u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadAddress); // ReadId code + u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadAddress); // ObjectId code + u8BytesLeft = 12; + break; } switch(u8MBFunction) @@ -730,7 +800,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) } // evaluate slave ID, function code once enough bytes have been read - if (u8ModbusADUSize == 5) + if ((u8ModbusADUSize == 5) && (u8ModbusADU[1] != ku8MBReadDeviceIdentifiers)) { // verify response is for correct Modbus slave if (u8ModbusADU[0] != _u8MBSlave) @@ -774,9 +844,27 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) case ku8MBMaskWriteRegister: u8BytesLeft = 5; break; + break; + } + } + if (u8ModbusADU[1] == ku8MBReadDeviceIdentifiers) // function 2B-0E + { + if ((u8ModbusADUSize == 8) && (u8RDIobjcnt == 0)) + { + u8RDIobjcnt = u8ModbusADU[7]; + u8BytesLeft = u8RDIobjcnt * 2 + 2; + u8RDInextObjSzIdx = u8ModbusADUSize + 2; + } + if ((u8ModbusADUSize == u8RDInextObjSzIdx) && (u8RDIobjcnt != 0)) + { + u8BytesLeft += u8ModbusADU[u8ModbusADUSize - 1]; + if (--u8RDIobjcnt != 0) + { + u8RDInextObjSzIdx += u8ModbusADU[u8ModbusADUSize - 1] + 2; + } } } - if ((millis() - u32StartTime) > ku16MBResponseTimeout) + if ((millis() - u32StartTime) > _u16ResponseTimeout) { u8MBStatus = ku8MBResponseTimedOut; } @@ -878,6 +966,30 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) _u8ResponseBufferLength = i; } break; + case ku8MBReadDeviceIdentifiers: + // The payload data of this function is a linked list of mostly ascii strings + // Here we concatenate the passed device ID strings, separated by spaces, and return to the caller. + u8RDIobjcnt = u8ModbusADU[7]; + u8RDInextObjSzIdx = 7 + 2; + *_pu8ReadStrSize = 0; + _u8ResponseBufferIndex = 0; + for (i = 0; i < u8RDIobjcnt; i++) + { + int len = u8ModbusADU[u8RDInextObjSzIdx]; + if ((len > 2) && (_u8ResponseBufferIndex + len < _u8ReadStrBufferMaxSize)) + { + if (_u8ResponseBufferIndex > 0) + { + _pu8ReadStrBuffer[_u8ResponseBufferIndex++] = ' '; + } + memcpy(_pu8ReadStrBuffer + _u8ResponseBufferIndex, u8ModbusADU + u8RDInextObjSzIdx + 1, len); + _u8ResponseBufferIndex += len; + _pu8ReadStrBuffer[_u8ResponseBufferIndex] = 0; + } + u8RDInextObjSzIdx += len + 2; + *_pu8ReadStrSize = _u8ResponseBufferIndex; + } + break; } } diff --git a/src/ModbusMaster.h b/src/ModbusMaster.h index e2cf017..e67d3e9 100644 --- a/src/ModbusMaster.h +++ b/src/ModbusMaster.h @@ -232,9 +232,14 @@ class ModbusMaster static const uint8_t ku8MBInvalidCRC = 0xE3; uint16_t getResponseBuffer(uint8_t Index); + uint8_t getResponseSize(void); void clearResponseBuffer(void); uint8_t setTransmitBuffer(uint8_t Offset, uint16_t Value); void clearTransmitBuffer(void); + void setSlaveId(uint8_t slaveid); + uint8_t getSlaveId(void); + uint16_t getResponseTimeout(void); + void setResponseTimeout(uint16_t timeout_ms); void beginTransmission(uint16_t u16Address); //uint8_t requestFrom(uint16_t Addr, uint16_t Qty); @@ -258,6 +263,8 @@ class ModbusMaster uint8_t maskWriteRegister(uint16_t u16WriteAddress, uint16_t u16AndMask, uint16_t u16OrMask); uint8_t readWriteMultipleRegisters(uint16_t u16ReadAddress, uint16_t u16ReadQty, uint16_t u16WriteAddress, uint16_t u16WriteQty); uint8_t readWriteMultipleRegisters(uint16_t Addr, uint16_t Qty); + //uint8_t readDeviceIdentifiers(uint8_t ReadId, uint8_t ObjectId); + uint8_t readDeviceIdentifiers(uint8_t ReadId, uint8_t ObjectId, char *pu8ReadStrBuffer, uint8_t u8ReadStrBufferMaxSize, uint8_t *pu8ReadStrSize); private: Stream* _serial; ///< reference to serial port object @@ -273,6 +280,10 @@ class ModbusMaster uint16_t u16TransmitBufferLength; uint8_t _u8ResponseBufferIndex; uint8_t _u8ResponseBufferLength; + char *_pu8ReadStrBuffer; + uint8_t _u8ReadStrBufferMaxSize; + uint8_t *_pu8ReadStrSize; + uint16_t _u16ResponseTimeout; // Modbus function codes for bit access static const uint8_t ku8MBReadCoils = 0x01; ///< Modbus function 0x01 Read Coils @@ -288,8 +299,10 @@ class ModbusMaster static const uint8_t ku8MBMaskWriteRegister = 0x16; ///< Modbus function 0x16 Mask Write Register static const uint8_t ku8MBReadWriteMultipleRegisters = 0x17; ///< Modbus function 0x17 Read Write Multiple Registers + static const uint8_t ku8MBReadDeviceIdentifiers = 0x2B; ///< Modbus function 0x2B/0E Read DeviceIdentifiers + // Modbus timeout [milliseconds] - static const uint16_t ku16MBResponseTimeout = 2000; ///< Modbus timeout [milliseconds] + static const uint16_t ku16MBDefaultResponseTimeout = 2000; ///< Modbus timeout [milliseconds] // master function that conducts Modbus transactions uint8_t ModbusMasterTransaction(uint8_t u8MBFunction); From 148e4004b731e3ed08de841e666f023a634d4a41 Mon Sep 17 00:00:00 2001 From: rob040 Date: Wed, 22 Feb 2023 16:04:32 +0100 Subject: [PATCH 5/6] Fix value returned by getResponseSize(), and usage of available() and receive() has now been fixed. Apparently never tested. This solves https://github.com/4-20ma/ModbusMaster/pull/154/commits/e15a1dce6d3e9db466cce5e157f326bb1d2556ee in a different, more robust way, by taking it out of the for loop and including the MaxBufferSize check. Fix description of getResponseSize(). --- src/ModbusMaster.cpp | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/src/ModbusMaster.cpp b/src/ModbusMaster.cpp index 12516da..ef46bf9 100644 --- a/src/ModbusMaster.cpp +++ b/src/ModbusMaster.cpp @@ -205,7 +205,7 @@ uint16_t ModbusMaster::getResponseBuffer(uint8_t u8Index) Get number of words in response buffer. @see ModbusMaster::getResponseBuffer -@return value in position u8Index of response buffer (0x0000..0xFFFF) +@return number of words in response buffer @ingroup buffer */ uint8_t ModbusMaster::getResponseSize() @@ -880,8 +880,9 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) } DebugSerial.println(); bool blprintstr = false; - i = (u8ModbusADU[1] == ku8MBReadDeviceIdentifiers) ? 10 : 3; - for (; i < u8ModbusADUSize; i++) + if (u8ModbusADU[1] == ku8MBReadDeviceIdentifiers) { + /* ASCII translation of payload */ + for (i = 10; i < u8ModbusADUSize; i++) { if ((u8ModbusADU[i] >= ' ') && (u8ModbusADU[i] <= 'z')) { @@ -899,6 +900,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) } } DebugSerial.println(); + } DebugSerial.print("Status:"); DebugSerial.println(u8MBStatus, HEX); #endif @@ -930,24 +932,16 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) case ku8MBReadCoils: case ku8MBReadDiscreteInputs: // load bytes into word; response bytes are ordered L, H, L, H, ... - for (i = 0; i < (u8ModbusADU[2] >> 1); i++) + for (i = 0; (i < (u8ModbusADU[2] >> 1)) && (i < ku8MaxBufferSize); i++) { - if (i < ku8MaxBufferSize) - { - _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 4], u8ModbusADU[2 * i + 3]); - } - - _u8ResponseBufferLength = i; + _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 4], u8ModbusADU[2 * i + 3]); } + _u8ResponseBufferLength = i; // in the event of an odd number of bytes, load last byte into zero-padded word - if (u8ModbusADU[2] % 2) + if ((u8ModbusADU[2] % 2) && (i < ku8MaxBufferSize)) { - if (i < ku8MaxBufferSize) - { - _u16ResponseBuffer[i] = word(0, u8ModbusADU[2 * i + 3]); - } - + _u16ResponseBuffer[i] = word(0, u8ModbusADU[2 * i + 3]); _u8ResponseBufferLength = i + 1; } break; @@ -956,15 +950,11 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) case ku8MBReadHoldingRegisters: case ku8MBReadWriteMultipleRegisters: // load bytes into word; response bytes are ordered H, L, H, L, ... - for (i = 0; i < (u8ModbusADU[2] >> 1); i++) + for (i = 0; (i < (u8ModbusADU[2] >> 1)) && (i < ku8MaxBufferSize); i++) { - if (i < ku8MaxBufferSize) - { - _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 3], u8ModbusADU[2 * i + 4]); - } - - _u8ResponseBufferLength = i; + _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 3], u8ModbusADU[2 * i + 4]); } + _u8ResponseBufferLength = i; break; case ku8MBReadDeviceIdentifiers: // The payload data of this function is a linked list of mostly ascii strings From 01baa9c79fba1321affeb79e970234cef04b70ef Mon Sep 17 00:00:00 2001 From: rob040 Date: Wed, 22 Feb 2023 16:09:08 +0100 Subject: [PATCH 6/6] increase library version; still backwards compatible --- keywords.txt | 1 + library.properties | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/keywords.txt b/keywords.txt index cf50a0a..fe514a4 100644 --- a/keywords.txt +++ b/keywords.txt @@ -33,6 +33,7 @@ writeMultipleCoils KEYWORD2 writeMultipleRegisters KEYWORD2 maskWriteRegister KEYWORD2 readWriteMultipleRegisters KEYWORD2 +readDeviceIdentifiers KEYWORD2 ####################################### # Constants (LITERAL1) diff --git a/library.properties b/library.properties index a2be2fa..b21da80 100644 --- a/library.properties +++ b/library.properties @@ -1,6 +1,6 @@ name=ModbusMaster -version=2.0.1 -author=Doc Walker +version=2.0.2 +author=Doc Walker & robl040 maintainer=Doc Walker <4-20ma@wvfans.net> sentence=Enlighten your Arduino to be a Modbus master. paragraph=Enables communication with Modbus slaves over RS232/485 (via RTU protocol). Requires an RS232/485 transceiver.