From aa61abd7f126ad8ca82a9c1b513b5c403385ec77 Mon Sep 17 00:00:00 2001 From: Fake-Name Date: Sat, 4 Aug 2018 23:47:28 -0700 Subject: [PATCH] You kind of need the ability to have multiple modbus slaves. Modbus is pointless without it. Also, use the serial's built-in send-many call. --- src/ModbusMaster.cpp | 174 ++++++++++++++++++++++--------------------- src/ModbusMaster.h | 115 ++++++++++++++-------------- 2 files changed, 149 insertions(+), 140 deletions(-) diff --git a/src/ModbusMaster.cpp b/src/ModbusMaster.cpp index 4169e58..339b156 100644 --- a/src/ModbusMaster.cpp +++ b/src/ModbusMaster.cpp @@ -65,7 +65,7 @@ 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); @@ -247,7 +247,7 @@ Clear Modbus response buffer. void ModbusMaster::clearResponseBuffer() { uint8_t i; - + for (i = 0; i < ku8MaxBufferSize; i++) { _u16ResponseBuffer[i] = 0; @@ -287,7 +287,7 @@ Clear Modbus transmit buffer. void ModbusMaster::clearTransmitBuffer() { uint8_t i; - + for (i = 0; i < ku8MaxBufferSize; i++) { _u16TransmitBuffer[i] = 0; @@ -295,22 +295,32 @@ void ModbusMaster::clearTransmitBuffer() } +/** + + Change the remote modbus slave id. + */ +void ModbusMaster::setSlaveId(uint8_t slave_id) +{ + this->_u8MBSlave = slave_id; +} + + /** 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) @@ -329,19 +339,19 @@ uint8_t ModbusMaster::readCoils(uint16_t u16ReadAddress, uint16_t u16BitQty) /** 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) @@ -361,12 +371,12 @@ uint8_t ModbusMaster::readDiscreteInputs(uint16_t u16ReadAddress, /** 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) @@ -386,12 +396,12 @@ uint8_t ModbusMaster::readHoldingRegisters(uint16_t u16ReadAddress, /** 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) @@ -411,10 +421,10 @@ uint8_t ModbusMaster::readInputRegisters(uint16_t u16ReadAddress, /** 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) @@ -433,8 +443,8 @@ uint8_t ModbusMaster::writeSingleCoil(uint16_t u16WriteAddress, uint8_t u8State) /** 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) @@ -455,12 +465,12 @@ uint8_t ModbusMaster::writeSingleRegister(uint16_t u16WriteAddress, /** 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) @@ -485,10 +495,10 @@ uint8_t ModbusMaster::writeMultipleCoils() /** 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) @@ -515,13 +525,13 @@ uint8_t ModbusMaster::writeMultipleRegisters() /** 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: @@ -547,14 +557,14 @@ uint8_t ModbusMaster::maskWriteRegister(uint16_t u16WriteAddress, /** 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 +616,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 +634,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadQty); break; } - + switch(u8MBFunction) { case ku8MBWriteSingleCoil: @@ -637,19 +647,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 +672,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 +700,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[1]); break; } - + // append CRC u16CRC = 0xFFFF; for (i = 0; i < u8ModbusADUSize; i++) @@ -709,18 +719,16 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) { _preTransmission(); } - for (i = 0; i < u8ModbusADUSize; i++) - { - _serial->write(u8ModbusADU[i]); - } - + + _serial->write(u8ModbusADU, u8ModbusADUSize); + 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 +757,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 +767,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 +792,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 +810,7 @@ uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction) u8MBStatus = ku8MBResponseTimedOut; } } - + // verify response is large enough to inspect further if (!u8MBStatus && u8ModbusADUSize >= 5) { @@ -812,7 +820,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 +844,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 +855,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 +870,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..d9f5459 100644 --- a/src/ModbusMaster.h +++ b/src/ModbusMaster.h @@ -31,7 +31,7 @@ Arduino library for communicating with Modbus slaves over RS232/485 (via RTU pro */ - + #ifndef ModbusMaster_h #define ModbusMaster_h @@ -63,14 +63,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 +79,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 +139,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 +201,9 @@ class ModbusMaster void send(uint32_t); uint8_t available(void); uint16_t receive(void); - - + + void setSlaveId(uint8_t); + uint8_t readCoils(uint16_t, uint16_t); uint8_t readDiscreteInputs(uint16_t, uint16_t); uint8_t readHoldingRegisters(uint16_t, uint16_t); @@ -216,11 +217,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 +234,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 +248,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