Advertisement
RuiViana

ModbusMaster.cpp_Modificado

Feb 26th, 2016
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.98 KB | None | 0 0
  1. /**
  2. @file
  3. Arduino library for communicating with Modbus slaves over RS232/485 (via RTU protocol).
  4. */
  5. /*
  6.  
  7. ModbusMaster.cpp - Arduino library for communicating with Modbus slaves
  8. over RS232/485 (via RTU protocol).
  9.  
  10. This file is part of ModbusMaster.
  11.  
  12. ModbusMaster is free software: you can redistribute it and/or modify
  13. it under the terms of the GNU General Public License as published by
  14. the Free Software Foundation, either version 3 of the License, or
  15. (at your option) any later version.
  16.  
  17. ModbusMaster is distributed in the hope that it will be useful,
  18. but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. GNU General Public License for more details.
  21.  
  22. You should have received a copy of the GNU General Public License
  23. along with ModbusMaster. If not, see <http://www.gnu.org/licenses/>.
  24.  
  25. Written by Doc Walker (Rx)
  26. Copyright © 2009-2013 Doc Walker <4-20ma at wvfans dot net>
  27.  
  28. */
  29.  
  30.  
  31. /* _____PROJECT INCLUDES_____________________________________________________ */
  32. #include "ModbusMaster.h"
  33.  
  34.  
  35. /* _____GLOBAL VARIABLES_____________________________________________________ */
  36. #if defined(ARDUINO_ARCH_AVR)
  37. HardwareSerial* MBSerial = &Serial; ///< Pointer to Serial class object
  38. #elif defined(ARDUINO_ARCH_SAM)
  39. UARTClass* MBSerial = &Serial; ///< Pointer to Serial class object
  40. #else
  41. #error "This library only supports boards with an AVR or SAM processor. Please open an issue at https://github.com/4-20ma/ModbusMaster/issues and indicate which processor/platform you're using."
  42. #endif
  43.  
  44.  
  45. /* _____PUBLIC FUNCTIONS_____________________________________________________ */
  46. /**
  47. Constructor.
  48.  
  49. Creates class object using default serial port 0, Modbus slave ID 1.
  50.  
  51. @ingroup setup
  52. */
  53. ModbusMaster::ModbusMaster(void)
  54. {
  55. _u8SerialPort = 0;
  56. _u8MBSlave = 1;
  57. }
  58.  
  59.  
  60. /**
  61. Constructor.
  62.  
  63. Creates class object using default serial port 0, specified Modbus slave ID.
  64.  
  65. @overload void ModbusMaster::ModbusMaster(uint8_t u8MBSlave)
  66. @param u8MBSlave Modbus slave ID (1..255)
  67. @ingroup setup
  68. */
  69. ModbusMaster::ModbusMaster(uint8_t u8MBSlave)
  70. {
  71. _u8SerialPort = 0;
  72. _u8MBSlave = u8MBSlave;
  73. }
  74.  
  75.  
  76. /**
  77. Constructor.
  78.  
  79. Creates class object using specified serial port, Modbus slave ID.
  80.  
  81. @overload void ModbusMaster::ModbusMaster(uint8_t u8SerialPort, uint8_t u8MBSlave)
  82. @param u8SerialPort serial port (Serial, Serial1..Serial3)
  83. @param u8MBSlave Modbus slave ID (1..255)
  84. @ingroup setup
  85. */
  86. ModbusMaster::ModbusMaster(uint8_t u8SerialPort, uint8_t u8MBSlave)
  87. {
  88. _u8SerialPort = (u8SerialPort > 3) ? 0 : u8SerialPort;
  89. _u8MBSlave = u8MBSlave;
  90. }
  91.  
  92.  
  93. /**
  94. Initialize class object.
  95.  
  96. Sets up the serial port using default 19200 baud rate.
  97. Call once class has been instantiated, typically within setup().
  98.  
  99. @ingroup setup
  100. */
  101. void ModbusMaster::begin(void)
  102. {
  103. begin(19200);
  104. }
  105.  
  106.  
  107. /**
  108. Initialize class object.
  109.  
  110. Sets up the serial port using specified baud rate.
  111. Call once class has been instantiated, typically within setup().
  112.  
  113. @overload ModbusMaster::begin(uint16_t u16BaudRate)
  114. @param u16BaudRate baud rate, in standard increments (300..115200)
  115. @ingroup setup
  116. */
  117. void ModbusMaster::begin(uint16_t u16BaudRate)
  118. {
  119. // txBuffer = (uint16_t*) calloc(ku8MaxBufferSize, sizeof(uint16_t));
  120. _u8TransmitBufferIndex = 0;
  121. u16TransmitBufferLength = 0;
  122.  
  123. switch(_u8SerialPort)
  124. {
  125. #if defined(UBRR1H)
  126. case 1:
  127. MBSerial = &Serial1;
  128. break;
  129. #endif
  130.  
  131. #if defined(UBRR2H)
  132. case 2:
  133. MBSerial = &Serial2;
  134. break;
  135. #endif
  136.  
  137. #if defined(UBRR3H)
  138. case 3:
  139. MBSerial = &Serial3;
  140. break;
  141. #endif
  142.  
  143. case 0:
  144. default:
  145. MBSerial = &Serial;
  146. break;
  147. }
  148.  
  149. MBSerial->begin(u16BaudRate);
  150. #if __MODBUSMASTER_DEBUG__
  151. pinMode(4, OUTPUT);
  152. pinMode(5, OUTPUT);
  153. pinMode(6, OUTPUT); // <<---------------------------------------- Alterei
  154. #endif
  155. }
  156.  
  157.  
  158. void ModbusMaster::beginTransmission(uint16_t u16Address)
  159. {
  160. _u16WriteAddress = u16Address;
  161. _u8TransmitBufferIndex = 0;
  162. u16TransmitBufferLength = 0;
  163. }
  164.  
  165. // eliminate this function in favor of using existing MB request functions
  166. uint8_t ModbusMaster::requestFrom(uint16_t address, uint16_t quantity)
  167. {
  168. uint8_t read;
  169. // clamp to buffer length
  170. if (quantity > ku8MaxBufferSize)
  171. {
  172. quantity = ku8MaxBufferSize;
  173. }
  174. // set rx buffer iterator vars
  175. _u8ResponseBufferIndex = 0;
  176. _u8ResponseBufferLength = read;
  177.  
  178. return read;
  179. }
  180.  
  181.  
  182. void ModbusMaster::sendBit(bool data)
  183. {
  184. uint8_t txBitIndex = u16TransmitBufferLength % 16;
  185. if ((u16TransmitBufferLength >> 4) < ku8MaxBufferSize)
  186. {
  187. if (0 == txBitIndex)
  188. {
  189. _u16TransmitBuffer[_u8TransmitBufferIndex] = 0;
  190. }
  191. bitWrite(_u16TransmitBuffer[_u8TransmitBufferIndex], txBitIndex, data);
  192. u16TransmitBufferLength++;
  193. _u8TransmitBufferIndex = u16TransmitBufferLength >> 4;
  194. }
  195. }
  196.  
  197.  
  198. void ModbusMaster::send(uint16_t data)
  199. {
  200. if (_u8TransmitBufferIndex < ku8MaxBufferSize)
  201. {
  202. _u16TransmitBuffer[_u8TransmitBufferIndex++] = data;
  203. u16TransmitBufferLength = _u8TransmitBufferIndex << 4;
  204. }
  205. }
  206.  
  207.  
  208. void ModbusMaster::send(uint32_t data)
  209. {
  210. send(lowWord(data));
  211. send(highWord(data));
  212. }
  213.  
  214.  
  215. void ModbusMaster::send(uint8_t data)
  216. {
  217. send(word(data));
  218. }
  219.  
  220.  
  221.  
  222.  
  223.  
  224.  
  225.  
  226.  
  227.  
  228. uint8_t ModbusMaster::available(void)
  229. {
  230. return _u8ResponseBufferLength - _u8ResponseBufferIndex;
  231. }
  232.  
  233.  
  234. uint16_t ModbusMaster::receive(void)
  235. {
  236. if (_u8ResponseBufferIndex < _u8ResponseBufferLength)
  237. {
  238. return _u16ResponseBuffer[_u8ResponseBufferIndex++];
  239. }
  240. else
  241. {
  242. return 0xFFFF;
  243. }
  244. }
  245.  
  246.  
  247.  
  248.  
  249.  
  250.  
  251.  
  252.  
  253. /**
  254. Set idle time callback function (cooperative multitasking).
  255.  
  256. This function gets called in the idle time between transmission of data
  257. and response from slave. Do not call functions that read from the serial
  258. buffer that is used by ModbusMaster. Use of i2c/TWI, 1-Wire, other
  259. serial ports, etc. is permitted within callback function.
  260.  
  261. @see ModbusMaster::ModbusMasterTransaction()
  262. */
  263. void ModbusMaster::idle(void (*idle)())
  264. {
  265. _idle = idle;
  266. }
  267.  
  268.  
  269. /**
  270. Retrieve data from response buffer.
  271.  
  272. @see ModbusMaster::clearResponseBuffer()
  273. @param u8Index index of response buffer array (0x00..0x3F)
  274. @return value in position u8Index of response buffer (0x0000..0xFFFF)
  275. @ingroup buffer
  276. */
  277. uint16_t ModbusMaster::getResponseBuffer(uint8_t u8Index)
  278. {
  279. if (u8Index < ku8MaxBufferSize)
  280. {
  281. return _u16ResponseBuffer[u8Index];
  282. }
  283. else
  284. {
  285. return 0xFFFF;
  286. }
  287. }
  288.  
  289.  
  290. /**
  291. Clear Modbus response buffer.
  292.  
  293. @see ModbusMaster::getResponseBuffer(uint8_t u8Index)
  294. @ingroup buffer
  295. */
  296. void ModbusMaster::clearResponseBuffer()
  297. {
  298. uint8_t i;
  299.  
  300. for (i = 0; i < ku8MaxBufferSize; i++)
  301. {
  302. _u16ResponseBuffer[i] = 0;
  303. }
  304. }
  305.  
  306.  
  307. /**
  308. Place data in transmit buffer.
  309.  
  310. @see ModbusMaster::clearTransmitBuffer()
  311. @param u8Index index of transmit buffer array (0x00..0x3F)
  312. @param u16Value value to place in position u8Index of transmit buffer (0x0000..0xFFFF)
  313. @return 0 on success; exception number on failure
  314. @ingroup buffer
  315. */
  316. uint8_t ModbusMaster::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value)
  317. {
  318. if (u8Index < ku8MaxBufferSize)
  319. {
  320. _u16TransmitBuffer[u8Index] = u16Value;
  321. return ku8MBSuccess;
  322. }
  323. else
  324. {
  325. return ku8MBIllegalDataAddress;
  326. }
  327. }
  328.  
  329.  
  330. /**
  331. Clear Modbus transmit buffer.
  332.  
  333. @see ModbusMaster::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value)
  334. @ingroup buffer
  335. */
  336. void ModbusMaster::clearTransmitBuffer()
  337. {
  338. uint8_t i;
  339.  
  340. for (i = 0; i < ku8MaxBufferSize; i++)
  341. {
  342. _u16TransmitBuffer[i] = 0;
  343. }
  344. }
  345.  
  346.  
  347. /**
  348. Modbus function 0x01 Read Coils.
  349.  
  350. This function code is used to read from 1 to 2000 contiguous status of
  351. coils in a remote device. The request specifies the starting address,
  352. i.e. the address of the first coil specified, and the number of coils.
  353. Coils are addressed starting at zero.
  354.  
  355. The coils in the response buffer are packed as one coil per bit of the
  356. data field. Status is indicated as 1=ON and 0=OFF. The LSB of the first
  357. data word contains the output addressed in the query. The other coils
  358. follow toward the high order end of this word and from low order to high
  359. order in subsequent words.
  360.  
  361. If the returned quantity is not a multiple of sixteen, the remaining
  362. bits in the final data word will be padded with zeros (toward the high
  363. order end of the word).
  364.  
  365. @param u16ReadAddress address of first coil (0x0000..0xFFFF)
  366. @param u16BitQty quantity of coils to read (1..2000, enforced by remote device)
  367. @return 0 on success; exception number on failure
  368. @ingroup discrete
  369. */
  370. uint8_t ModbusMaster::readCoils(uint16_t u16ReadAddress, uint16_t u16BitQty)
  371. {
  372. _u16ReadAddress = u16ReadAddress;
  373. _u16ReadQty = u16BitQty;
  374. return ModbusMasterTransaction(ku8MBReadCoils);
  375. }
  376.  
  377.  
  378. /**
  379. Modbus function 0x02 Read Discrete Inputs.
  380.  
  381. This function code is used to read from 1 to 2000 contiguous status of
  382. discrete inputs in a remote device. The request specifies the starting
  383. address, i.e. the address of the first input specified, and the number
  384. of inputs. Discrete inputs are addressed starting at zero.
  385.  
  386. The discrete inputs in the response buffer are packed as one input per
  387. bit of the data field. Status is indicated as 1=ON; 0=OFF. The LSB of
  388. the first data word contains the input addressed in the query. The other
  389. inputs follow toward the high order end of this word, and from low order
  390. to high order in subsequent words.
  391.  
  392. If the returned quantity is not a multiple of sixteen, the remaining
  393. bits in the final data word will be padded with zeros (toward the high
  394. order end of the word).
  395.  
  396. @param u16ReadAddress address of first discrete input (0x0000..0xFFFF)
  397. @param u16BitQty quantity of discrete inputs to read (1..2000, enforced by remote device)
  398. @return 0 on success; exception number on failure
  399. @ingroup discrete
  400. */
  401. uint8_t ModbusMaster::readDiscreteInputs(uint16_t u16ReadAddress,
  402. uint16_t u16BitQty)
  403. {
  404. _u16ReadAddress = u16ReadAddress;
  405. _u16ReadQty = u16BitQty;
  406. return ModbusMasterTransaction(ku8MBReadDiscreteInputs);
  407. }
  408.  
  409.  
  410. /**
  411. Modbus function 0x03 Read Holding Registers.
  412.  
  413. This function code is used to read the contents of a contiguous block of
  414. holding registers in a remote device. The request specifies the starting
  415. register address and the number of registers. Registers are addressed
  416. starting at zero.
  417.  
  418. The register data in the response buffer is packed as one word per
  419. register.
  420.  
  421. @param u16ReadAddress address of the first holding register (0x0000..0xFFFF)
  422. @param u16ReadQty quantity of holding registers to read (1..125, enforced by remote device)
  423. @return 0 on success; exception number on failure
  424. @ingroup register
  425. */
  426. uint8_t ModbusMaster::readHoldingRegisters(uint16_t u16ReadAddress,
  427. uint16_t u16ReadQty)
  428. {
  429. _u16ReadAddress = u16ReadAddress;
  430. _u16ReadQty = u16ReadQty;
  431. return ModbusMasterTransaction(ku8MBReadHoldingRegisters);
  432. }
  433.  
  434.  
  435. /**
  436. Modbus function 0x04 Read Input Registers.
  437.  
  438. This function code is used to read from 1 to 125 contiguous input
  439. registers in a remote device. The request specifies the starting
  440. register address and the number of registers. Registers are addressed
  441. starting at zero.
  442.  
  443. The register data in the response buffer is packed as one word per
  444. register.
  445.  
  446. @param u16ReadAddress address of the first input register (0x0000..0xFFFF)
  447. @param u16ReadQty quantity of input registers to read (1..125, enforced by remote device)
  448. @return 0 on success; exception number on failure
  449. @ingroup register
  450. */
  451. uint8_t ModbusMaster::readInputRegisters(uint16_t u16ReadAddress,
  452. uint8_t u16ReadQty)
  453. {
  454. _u16ReadAddress = u16ReadAddress;
  455. _u16ReadQty = u16ReadQty;
  456. return ModbusMasterTransaction(ku8MBReadInputRegisters);
  457. }
  458.  
  459.  
  460. /**
  461. Modbus function 0x05 Write Single Coil.
  462.  
  463. This function code is used to write a single output to either ON or OFF
  464. in a remote device. The requested ON/OFF state is specified by a
  465. constant in the state field. A non-zero value requests the output to be
  466. ON and a value of 0 requests it to be OFF. The request specifies the
  467. address of the coil to be forced. Coils are addressed starting at zero.
  468.  
  469. @param u16WriteAddress address of the coil (0x0000..0xFFFF)
  470. @param u8State 0=OFF, non-zero=ON (0x00..0xFF)
  471. @return 0 on success; exception number on failure
  472. @ingroup discrete
  473. */
  474. uint8_t ModbusMaster::writeSingleCoil(uint16_t u16WriteAddress, uint8_t u8State)
  475. {
  476. _u16WriteAddress = u16WriteAddress;
  477. _u16WriteQty = (u8State ? 0xFF00 : 0x0000);
  478. return ModbusMasterTransaction(ku8MBWriteSingleCoil);
  479. }
  480.  
  481.  
  482. /**
  483. Modbus function 0x06 Write Single Register.
  484.  
  485. This function code is used to write a single holding register in a
  486. remote device. The request specifies the address of the register to be
  487. written. Registers are addressed starting at zero.
  488.  
  489. @param u16WriteAddress address of the holding register (0x0000..0xFFFF)
  490. @param u16WriteValue value to be written to holding register (0x0000..0xFFFF)
  491. @return 0 on success; exception number on failure
  492. @ingroup register
  493. */
  494. uint8_t ModbusMaster::writeSingleRegister(uint16_t u16WriteAddress,
  495. uint16_t u16WriteValue)
  496. {
  497. _u16WriteAddress = u16WriteAddress;
  498. _u16WriteQty = 0;
  499. _u16TransmitBuffer[0] = u16WriteValue;
  500. return ModbusMasterTransaction(ku8MBWriteSingleRegister);
  501. }
  502.  
  503.  
  504. /**
  505. Modbus function 0x0F Write Multiple Coils.
  506.  
  507. This function code is used to force each coil in a sequence of coils to
  508. either ON or OFF in a remote device. The request specifies the coil
  509. references to be forced. Coils are addressed starting at zero.
  510.  
  511. The requested ON/OFF states are specified by contents of the transmit
  512. buffer. A logical '1' in a bit position of the buffer requests the
  513. corresponding output to be ON. A logical '0' requests it to be OFF.
  514.  
  515. @param u16WriteAddress address of the first coil (0x0000..0xFFFF)
  516. @param u16BitQty quantity of coils to write (1..2000, enforced by remote device)
  517. @return 0 on success; exception number on failure
  518. @ingroup discrete
  519. */
  520. uint8_t ModbusMaster::writeMultipleCoils(uint16_t u16WriteAddress,
  521. uint16_t u16BitQty)
  522. {
  523. _u16WriteAddress = u16WriteAddress;
  524. _u16WriteQty = u16BitQty;
  525. return ModbusMasterTransaction(ku8MBWriteMultipleCoils);
  526. }
  527. uint8_t ModbusMaster::writeMultipleCoils()
  528. {
  529. _u16WriteQty = u16TransmitBufferLength;
  530. return ModbusMasterTransaction(ku8MBWriteMultipleCoils);
  531. }
  532.  
  533.  
  534. /**
  535. Modbus function 0x10 Write Multiple Registers.
  536.  
  537. This function code is used to write a block of contiguous registers (1
  538. to 123 registers) in a remote device.
  539.  
  540. The requested written values are specified in the transmit buffer. Data
  541. is packed as one word per register.
  542.  
  543. @param u16WriteAddress address of the holding register (0x0000..0xFFFF)
  544. @param u16WriteQty quantity of holding registers to write (1..123, enforced by remote device)
  545. @return 0 on success; exception number on failure
  546. @ingroup register
  547. */
  548. uint8_t ModbusMaster::writeMultipleRegisters(uint16_t u16WriteAddress,
  549. uint16_t u16WriteQty)
  550. {
  551. _u16WriteAddress = u16WriteAddress;
  552. _u16WriteQty = u16WriteQty;
  553. return ModbusMasterTransaction(ku8MBWriteMultipleRegisters);
  554. }
  555.  
  556. // new version based on Wire.h
  557. uint8_t ModbusMaster::writeMultipleRegisters()
  558. {
  559. _u16WriteQty = _u8TransmitBufferIndex;
  560. return ModbusMasterTransaction(ku8MBWriteMultipleRegisters);
  561. }
  562.  
  563.  
  564. /**
  565. Modbus function 0x16 Mask Write Register.
  566.  
  567. This function code is used to modify the contents of a specified holding
  568. register using a combination of an AND mask, an OR mask, and the
  569. register's current contents. The function can be used to set or clear
  570. individual bits in the register.
  571.  
  572. The request specifies the holding register to be written, the data to be
  573. used as the AND mask, and the data to be used as the OR mask. Registers
  574. are addressed starting at zero.
  575.  
  576. The function's algorithm is:
  577.  
  578. Result = (Current Contents && And_Mask) || (Or_Mask && (~And_Mask))
  579.  
  580. @param u16WriteAddress address of the holding register (0x0000..0xFFFF)
  581. @param u16AndMask AND mask (0x0000..0xFFFF)
  582. @param u16OrMask OR mask (0x0000..0xFFFF)
  583. @return 0 on success; exception number on failure
  584. @ingroup register
  585. */
  586. uint8_t ModbusMaster::maskWriteRegister(uint16_t u16WriteAddress,
  587. uint16_t u16AndMask, uint16_t u16OrMask)
  588. {
  589. _u16WriteAddress = u16WriteAddress;
  590. _u16TransmitBuffer[0] = u16AndMask;
  591. _u16TransmitBuffer[1] = u16OrMask;
  592. return ModbusMasterTransaction(ku8MBMaskWriteRegister);
  593. }
  594.  
  595.  
  596. /**
  597. Modbus function 0x17 Read Write Multiple Registers.
  598.  
  599. This function code performs a combination of one read operation and one
  600. write operation in a single MODBUS transaction. The write operation is
  601. performed before the read. Holding registers are addressed starting at
  602. zero.
  603.  
  604. The request specifies the starting address and number of holding
  605. registers to be read as well as the starting address, and the number of
  606. holding registers. The data to be written is specified in the transmit
  607. buffer.
  608.  
  609. @param u16ReadAddress address of the first holding register (0x0000..0xFFFF)
  610. @param u16ReadQty quantity of holding registers to read (1..125, enforced by remote device)
  611. @param u16WriteAddress address of the first holding register (0x0000..0xFFFF)
  612. @param u16WriteQty quantity of holding registers to write (1..121, enforced by remote device)
  613. @return 0 on success; exception number on failure
  614. @ingroup register
  615. */
  616. uint8_t ModbusMaster::readWriteMultipleRegisters(uint16_t u16ReadAddress,
  617. uint16_t u16ReadQty, uint16_t u16WriteAddress, uint16_t u16WriteQty)
  618. {
  619. _u16ReadAddress = u16ReadAddress;
  620. _u16ReadQty = u16ReadQty;
  621. _u16WriteAddress = u16WriteAddress;
  622. _u16WriteQty = u16WriteQty;
  623. return ModbusMasterTransaction(ku8MBReadWriteMultipleRegisters);
  624. }
  625. uint8_t ModbusMaster::readWriteMultipleRegisters(uint16_t u16ReadAddress,
  626. uint16_t u16ReadQty)
  627. {
  628. _u16ReadAddress = u16ReadAddress;
  629. _u16ReadQty = u16ReadQty;
  630. _u16WriteQty = _u8TransmitBufferIndex;
  631. return ModbusMasterTransaction(ku8MBReadWriteMultipleRegisters);
  632. }
  633.  
  634.  
  635. /* _____PRIVATE FUNCTIONS____________________________________________________ */
  636. /**
  637. Modbus transaction engine.
  638. Sequence:
  639. - assemble Modbus Request Application Data Unit (ADU),
  640. based on particular function called
  641. - transmit request over selected serial port
  642. - wait for/retrieve response
  643. - evaluate/disassemble response
  644. - return status (success/exception)
  645.  
  646. @param u8MBFunction Modbus function (0x01..0xFF)
  647. @return 0 on success; exception number on failure
  648. */
  649. //----------------------------------------------------------------------------------
  650. uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction)
  651. {
  652. uint8_t u8ModbusADU[256];
  653. uint8_t u8ModbusADUSize = 0;
  654. uint8_t i, u8Qty;
  655. uint16_t u16CRC;
  656. uint32_t u32StartTime;
  657. uint8_t u8BytesLeft = 8;
  658. uint8_t u8MBStatus = ku8MBSuccess;
  659.  
  660. // assemble Modbus Request Application Data Unit
  661. u8ModbusADU[u8ModbusADUSize++] = _u8MBSlave;
  662. u8ModbusADU[u8ModbusADUSize++] = u8MBFunction;
  663.  
  664. switch(u8MBFunction)
  665. {
  666. case ku8MBReadCoils:
  667. case ku8MBReadDiscreteInputs:
  668. case ku8MBReadInputRegisters:
  669. case ku8MBReadHoldingRegisters:
  670. case ku8MBReadWriteMultipleRegisters:
  671. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadAddress);
  672. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadAddress);
  673. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadQty);
  674. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadQty);
  675. break;
  676. }
  677.  
  678. switch(u8MBFunction)
  679. {
  680. case ku8MBWriteSingleCoil:
  681. case ku8MBMaskWriteRegister:
  682. case ku8MBWriteMultipleCoils:
  683. case ku8MBWriteSingleRegister:
  684. case ku8MBWriteMultipleRegisters:
  685. case ku8MBReadWriteMultipleRegisters:
  686. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteAddress);
  687. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteAddress);
  688. break;
  689. }
  690.  
  691. switch(u8MBFunction)
  692. {
  693. case ku8MBWriteSingleCoil:
  694. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty);
  695. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty);
  696. break;
  697.  
  698. case ku8MBWriteSingleRegister:
  699. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[0]);
  700. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[0]);
  701. break;
  702.  
  703. case ku8MBWriteMultipleCoils:
  704. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty);
  705. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty);
  706. u8Qty = (_u16WriteQty % 8) ? ((_u16WriteQty >> 3) + 1) : (_u16WriteQty >> 3);
  707. u8ModbusADU[u8ModbusADUSize++] = u8Qty;
  708. for (i = 0; i < u8Qty; i++)
  709. {
  710. switch(i % 2)
  711. {
  712. case 0: // i is even
  713. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[i >> 1]);
  714. break;
  715.  
  716. case 1: // i is odd
  717. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[i >> 1]);
  718. break;
  719. }
  720. }
  721. break;
  722.  
  723. case ku8MBWriteMultipleRegisters:
  724. case ku8MBReadWriteMultipleRegisters:
  725. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty);
  726. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty);
  727. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty << 1);
  728.  
  729. for (i = 0; i < lowByte(_u16WriteQty); i++)
  730. {
  731. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[i]);
  732. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[i]);
  733. }
  734. break;
  735.  
  736. case ku8MBMaskWriteRegister:
  737. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[0]);
  738. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[0]);
  739. u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[1]);
  740. u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[1]);
  741. break;
  742. }
  743.  
  744. // append CRC
  745. u16CRC = 0xFFFF;
  746. for (i = 0; i < u8ModbusADUSize; i++)
  747. {
  748. u16CRC = crc16_update(u16CRC, u8ModbusADU[i]);
  749. }
  750. u8ModbusADU[u8ModbusADUSize++] = lowByte(u16CRC);
  751. u8ModbusADU[u8ModbusADUSize++] = highByte(u16CRC);
  752. u8ModbusADU[u8ModbusADUSize] = 0;
  753.  
  754. // flush receive buffer before transmitting request
  755. while (MBSerial->read() != -1);
  756.  
  757. // transmit request
  758. for (i = 0; i < u8ModbusADUSize; i++)
  759. {
  760. #if defined(ARDUINO) && ARDUINO >= 100
  761. MBSerial->write(u8ModbusADU[i]);
  762. #else
  763. MBSerial->print(u8ModbusADU[i], BYTE);
  764. #endif
  765. }
  766.  
  767. u8ModbusADUSize = 0;
  768. MBSerial->flush(); // flush transmit buffer
  769.  
  770. // loop until we run out of time or bytes, or an error occurs
  771. u32StartTime = millis();
  772. while (u8BytesLeft && !u8MBStatus)
  773. {
  774. if (MBSerial->available())
  775. {
  776. #if __MODBUSMASTER_DEBUG__
  777. digitalWrite(4, true);
  778. #endif
  779. u8ModbusADU[u8ModbusADUSize++] = MBSerial->read();
  780. u8BytesLeft--;
  781. #if __MODBUSMASTER_DEBUG__
  782. digitalWrite(4, false);
  783. #endif
  784. }
  785. else
  786. {
  787. digitalWrite(6, false); // <<---------------------------------------- Alterei
  788. #if __MODBUSMASTER_DEBUG__
  789. digitalWrite(5, true); // <<---------------------------------------- original
  790. #endif
  791. if (_idle)
  792. {
  793. _idle();
  794. }
  795. #if __MODBUSMASTER_DEBUG__
  796. digitalWrite(5, false); // <<---------------------------------------- original
  797. #endif
  798. }
  799. // digitalWrite(6, false); // <<---------------------------------------- Alterei
  800.  
  801. // evaluate slave ID, function code once enough bytes have been read
  802. if (u8ModbusADUSize == 5)
  803. {
  804. // verify response is for correct Modbus slave
  805. if (u8ModbusADU[0] != _u8MBSlave)
  806. {
  807. u8MBStatus = ku8MBInvalidSlaveID;
  808. break;
  809. }
  810.  
  811. // verify response is for correct Modbus function code (mask exception bit 7)
  812. if ((u8ModbusADU[1] & 0x7F) != u8MBFunction)
  813. {
  814. u8MBStatus = ku8MBInvalidFunction;
  815. break;
  816. }
  817.  
  818. // check whether Modbus exception occurred; return Modbus Exception Code
  819. if (bitRead(u8ModbusADU[1], 7))
  820. {
  821. u8MBStatus = u8ModbusADU[2];
  822. break;
  823. }
  824.  
  825. // evaluate returned Modbus function code
  826. switch(u8ModbusADU[1])
  827. {
  828. case ku8MBReadCoils:
  829. case ku8MBReadDiscreteInputs:
  830. case ku8MBReadInputRegisters:
  831. case ku8MBReadHoldingRegisters:
  832. case ku8MBReadWriteMultipleRegisters:
  833. u8BytesLeft = u8ModbusADU[2];
  834. break;
  835.  
  836. case ku8MBWriteSingleCoil:
  837. case ku8MBWriteMultipleCoils:
  838. case ku8MBWriteSingleRegister:
  839. case ku8MBWriteMultipleRegisters:
  840. u8BytesLeft = 3;
  841. break;
  842.  
  843. case ku8MBMaskWriteRegister:
  844. u8BytesLeft = 5;
  845. break;
  846. }
  847. }
  848. if ((millis() - u32StartTime) > ku16MBResponseTimeout)
  849. {
  850. u8MBStatus = ku8MBResponseTimedOut;
  851. }
  852. }
  853. digitalWrite(6, true); // <<---------------------------------------- Alterei
  854. // verify response is large enough to inspect further
  855. if (!u8MBStatus && u8ModbusADUSize >= 5)
  856. {
  857. // calculate CRC
  858. u16CRC = 0xFFFF;
  859. for (i = 0; i < (u8ModbusADUSize - 2); i++)
  860. {
  861. u16CRC = crc16_update(u16CRC, u8ModbusADU[i]);
  862. }
  863.  
  864. // verify CRC
  865. if (!u8MBStatus && (lowByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 2] ||
  866. highByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 1]))
  867. {
  868. u8MBStatus = ku8MBInvalidCRC;
  869. }
  870. }
  871. // disassemble ADU into words
  872. if (!u8MBStatus)
  873. {
  874. // evaluate returned Modbus function code
  875. switch(u8ModbusADU[1])
  876. {
  877. case ku8MBReadCoils:
  878. case ku8MBReadDiscreteInputs:
  879. // load bytes into word; response bytes are ordered L, H, L, H, ...
  880. for (i = 0; i < (u8ModbusADU[2] >> 1); i++)
  881. {
  882. if (i < ku8MaxBufferSize)
  883. {
  884. _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 4], u8ModbusADU[2 * i + 3]);
  885. }
  886.  
  887. _u8ResponseBufferLength = i;
  888. }
  889.  
  890. // in the event of an odd number of bytes, load last byte into zero-padded word
  891. if (u8ModbusADU[2] % 2)
  892. {
  893. if (i < ku8MaxBufferSize)
  894. {
  895. _u16ResponseBuffer[i] = word(0, u8ModbusADU[2 * i + 3]);
  896. }
  897.  
  898. _u8ResponseBufferLength = i + 1;
  899. }
  900. break;
  901.  
  902. case ku8MBReadInputRegisters:
  903. case ku8MBReadHoldingRegisters:
  904. case ku8MBReadWriteMultipleRegisters:
  905. // load bytes into word; response bytes are ordered H, L, H, L, ...
  906. for (i = 0; i < (u8ModbusADU[2] >> 1); i++)
  907. {
  908. if (i < ku8MaxBufferSize)
  909. {
  910. _u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 3], u8ModbusADU[2 * i + 4]);
  911. }
  912.  
  913. _u8ResponseBufferLength = i;
  914. }
  915. break;
  916. }
  917. }
  918. _u8TransmitBufferIndex = 0;
  919. u16TransmitBufferLength = 0;
  920. _u8ResponseBufferIndex = 0;
  921. return u8MBStatus;
  922. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement