forked from OSCSYS/modbusmaster
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ModbusMaster.cpp
770 lines (637 loc) · 22.6 KB
/
ModbusMaster.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/**
@file
Arduino library for communicating with Modbus slaves over RS232/485 (via RTU protocol).
*/
/*
ModbusMaster.cpp - Arduino library for communicating with Modbus slaves
over RS232/485 (via RTU protocol).
This file is part of ModbusMaster.
ModbusMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ModbusMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ModbusMaster. If not, see <http://www.gnu.org/licenses/>.
Written by Doc Walker (Rx)
Copyright © 2009, 2010 Doc Walker <dfwmountaineers at gmail dot com>
$Id: ModbusMaster.cpp 39 2010-02-10 02:12:21Z dfwmountaineers $
*/
/* _____PROJECT INCLUDES_____________________________________________________ */
#include "ModbusMaster.h"
#include <pins_arduino.h>
/* _____GLOBAL VARIABLES_____________________________________________________ */
HardwareSerial MBSerial = Serial; ///< Pointer to Serial class object
/* _____PUBLIC FUNCTIONS_____________________________________________________ */
/**
Constructor.
Creates class object using default serial port 0, Modbus slave ID 1.
@ingroup setup
*/
ModbusMaster::ModbusMaster(void)
{
_u8SerialPort = 0;
_u8MBSlave = 1;
}
/**
Constructor.
Creates class object using default serial port 0, specified Modbus slave ID.
@overload void ModbusMaster::ModbusMaster(uint8_t u8MBSlave)
@param u8MBSlave Modbus slave ID (1..255)
@ingroup setup
*/
ModbusMaster::ModbusMaster(uint8_t u8MBSlave)
{
_u8SerialPort = 0;
_u8MBSlave = u8MBSlave;
}
/**
Constructor.
Creates class object using specified serial port, Modbus slave ID.
@overload void ModbusMaster::ModbusMaster(uint8_t u8SerialPort, uint8_t u8MBSlave)
@param u8SerialPort serial port (0..3)
@param u8MBSlave Modbus slave ID (1..255)
@ingroup setup
*/
ModbusMaster::ModbusMaster(uint8_t u8SerialPort, uint8_t u8MBSlave)
{
_u8SerialPort = (u8SerialPort > 3) ? 0 : u8SerialPort;
_u8MBSlave = u8MBSlave;
_u8RTSMask = 0; //Unused by default
}
/**
Initialize class object.
Sets up the serial port using default 19200 baud rate and no parity.
Call once class has been instantiated, typically within setup().
@ingroup setup
*/
void ModbusMaster::begin(void)
{
begin(19200, 'n');
}
//Default No Parity
void ModbusMaster::begin(uint32_t BaudRate)
{
begin(BaudRate, SERIAL_8N1);
}
/**
Initialize class object.
Sets up the serial port using specified baud rate.
Call once class has been instantiated, typically within setup().
@overload ModbusMaster::begin(uint16_t u16BaudRate, uint8_t parity)
@param u16BaudRate baud rate, in standard increments (300..115200)
@param parity 'n', 'e', 'o'
@ingroup setup
*/
void ModbusMaster::begin(uint32_t BaudRate, uint8_t config)
{
switch(_u8SerialPort)
{
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)
case 1:
MBSerial = Serial1;
break;
#endif
#if defined(__AVR_ATmega1280__)
case 2:
MBSerial = Serial2;
break;
case 3:
MBSerial = Serial3;
break;
#endif
case 0:
default:
MBSerial = Serial;
break;
}
MBSerial.begin(BaudRate, config);
}
void ModbusMaster::setupRTS(uint8_t pinID)
{
uint8_t portID;
portID = digitalPinToPort(pinID);
_u8RTSMask = digitalPinToBitMask(pinID);
_u8RTSPort = portOutputRegister(portID);
volatile uint8_t* pDDRx = portModeRegister(portID); //Get DDR Port
*pDDRx |= _u8RTSMask; //Set as output
}
/**
Retrieve data from response buffer.
@see ModbusMaster::clearResponseBuffer()
@param u8Index index of response buffer array (0x00..0x3F)
@return value in position u8Index of response buffer (0x0000..0xFFFF)
@ingroup buffer
*/
uint16_t ModbusMaster::getResponseBuffer(uint8_t u8Index)
{
if (u8Index < ku8MaxBufferSize)
{
return _u16ResponseBuffer[u8Index];
}
else
{
return 0xFFFF;
}
}
/**
Clear Modbus response buffer.
@see ModbusMaster::getResponseBuffer(uint8_t u8Index)
@ingroup buffer
*/
void ModbusMaster::clearResponseBuffer()
{
uint8_t i;
for (i = 0; i < ku8MaxBufferSize; i++)
{
_u16ResponseBuffer[i] = 0;
}
}
/**
Place data in transmit buffer.
@see ModbusMaster::clearTransmitBuffer()
@param u8Index index of transmit buffer array (0x00..0x3F)
@param u16Value value to place in position u8Index of transmit buffer (0x0000..0xFFFF)
@return 0 on success; exception number on failure
@ingroup buffer
*/
uint8_t ModbusMaster::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value)
{
if (u8Index < ku8MaxBufferSize)
{
_u16TransmitBuffer[u8Index] = u16Value;
return ku8MBSuccess;
}
else
{
return ku8MBIllegalDataAddress;
}
}
/**
Clear Modbus transmit buffer.
@see ModbusMaster::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value)
@ingroup buffer
*/
void ModbusMaster::clearTransmitBuffer()
{
uint8_t i;
for (i = 0; i < ku8MaxBufferSize; i++)
{
_u16TransmitBuffer[i] = 0;
}
}
/**
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.
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
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
order end of the word).
@param u16ReadAddress address of first coil (0x0000..0xFFFF)
@param u16BitQty quantity of coils to read (1..2000, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup discrete
*/
uint8_t ModbusMaster::readCoils(uint16_t u16ReadAddress, uint16_t u16BitQty)
{
_u16ReadAddress = u16ReadAddress;
_u16ReadQty = 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
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
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
order end of the word).
@param u16ReadAddress address of first discrete input (0x0000..0xFFFF)
@param u16BitQty quantity of discrete inputs to read (1..2000, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup discrete
*/
uint8_t ModbusMaster::readDiscreteInputs(uint16_t u16ReadAddress,
uint16_t u16BitQty)
{
_u16ReadAddress = u16ReadAddress;
_u16ReadQty = u16BitQty;
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
starting at zero.
The register data in the response buffer is packed as one word per
register.
@param u16ReadAddress address of the first holding register (0x0000..0xFFFF)
@param u16ReadQty quantity of holding registers to read (1..125, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup register
*/
uint8_t ModbusMaster::readHoldingRegisters(uint16_t u16ReadAddress,
uint16_t u16ReadQty)
{
_u16ReadAddress = u16ReadAddress;
_u16ReadQty = u16ReadQty;
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
starting at zero.
The register data in the response buffer is packed as one word per
register.
@param u16ReadAddress address of the first input register (0x0000..0xFFFF)
@param u16ReadQty quantity of input registers to read (1..125, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup register
*/
uint8_t ModbusMaster::readInputRegisters(uint16_t u16ReadAddress,
uint8_t u16ReadQty)
{
_u16ReadAddress = u16ReadAddress;
_u16ReadQty = u16ReadQty;
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
address of the coil to be forced. Coils are addressed starting at zero.
@param u16WriteAddress address of the coil (0x0000..0xFFFF)
@param u8State 0=OFF, non-zero=ON (0x00..0xFF)
@return 0 on success; exception number on failure
@ingroup discrete
*/
uint8_t ModbusMaster::writeSingleCoil(uint16_t u16WriteAddress, uint8_t u8State)
{
_u16WriteAddress = u16WriteAddress;
_u16WriteQty = (u8State ? 0xFF00 : 0x0000);
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
written. Registers are addressed starting at zero.
@param u16WriteAddress address of the holding register (0x0000..0xFFFF)
@param u16WriteValue value to be written to holding register (0x0000..0xFFFF)
@return 0 on success; exception number on failure
@ingroup register
*/
uint8_t ModbusMaster::writeSingleRegister(uint16_t u16WriteAddress,
uint16_t u16WriteValue)
{
_u16WriteAddress = u16WriteAddress;
_u16WriteQty = 0;
_u16TransmitBuffer[0] = u16WriteValue;
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
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
corresponding output to be ON. A logical '0' requests it to be OFF.
@param u16WriteAddress address of the first coil (0x0000..0xFFFF)
@param u16BitQty quantity of coils to write (1..2000, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup discrete
*/
uint8_t ModbusMaster::writeMultipleCoils(uint16_t u16WriteAddress,
uint16_t u16BitQty)
{
_u16WriteAddress = u16WriteAddress;
_u16WriteQty = u16BitQty;
return ModbusMasterTransaction(ku8MBWriteMultipleCoils);
}
/**
Modbus function 0x10 Write Multiple Registers.
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
is packed as one word per register.
@param u16WriteAddress address of the holding register (0x0000..0xFFFF)
@param u16WriteQty quantity of holding registers to write (1..123, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup register
*/
uint8_t ModbusMaster::writeMultipleRegisters(uint16_t u16WriteAddress,
uint16_t u16WriteQty)
{
_u16WriteAddress = u16WriteAddress;
_u16WriteQty = u16WriteQty;
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
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
are addressed starting at zero.
The function's algorithm is:
Result = (Current Contents && And_Mask) || (Or_Mask && (~And_Mask))
@param u16WriteAddress address of the holding register (0x0000..0xFFFF)
@param u16AndMask AND mask (0x0000..0xFFFF)
@param u16OrMask OR mask (0x0000..0xFFFF)
@return 0 on success; exception number on failure
@ingroup register
*/
uint8_t ModbusMaster::maskWriteRegister(uint16_t u16WriteAddress,
uint16_t u16AndMask, uint16_t u16OrMask)
{
_u16WriteAddress = u16WriteAddress;
_u16TransmitBuffer[0] = u16AndMask;
_u16TransmitBuffer[1] = u16OrMask;
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
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
buffer.
@param u16ReadAddress address of the first holding register (0x0000..0xFFFF)
@param u16ReadQty quantity of holding registers to read (1..125, enforced by remote device)
@param u16WriteAddress address of the first holding register (0x0000..0xFFFF)
@param u16WriteQty quantity of holding registers to write (1..121, enforced by remote device)
@return 0 on success; exception number on failure
@ingroup register
*/
uint8_t ModbusMaster::readWriteMultipleRegisters(uint16_t u16ReadAddress,
uint16_t u16ReadQty, uint16_t u16WriteAddress, uint16_t u16WriteQty)
{
_u16ReadAddress = u16ReadAddress;
_u16ReadQty = u16ReadQty;
_u16WriteAddress = u16WriteAddress;
_u16WriteQty = u16WriteQty;
return ModbusMasterTransaction(ku8MBReadWriteMultipleRegisters);
}
/* _____PRIVATE FUNCTIONS____________________________________________________ */
/**
Modbus transaction engine.
Sequence:
- assemble Modbus Request Application Data Unit (ADU),
based on particular function called
- transmit request over selected serial port
- wait for/retrieve response
- evaluate/disassemble response
- return status (success/exception)
@param u8MBFunction Modbus function (0x01..0xFF)
@return 0 on success; exception number on failure
*/
uint8_t ModbusMaster::ModbusMasterTransaction(uint8_t u8MBFunction)
{
uint8_t u8ModbusADU[256];
uint8_t u8ModbusADUSize = 0;
uint8_t i, u8Qty;
uint16_t u16CRC;
uint32_t u32RXStartTime;
uint8_t u8BytesLeft = 8;
uint8_t u8MBStatus = ku8MBSuccess;
// assemble Modbus Request Application Data Unit
u8ModbusADU[u8ModbusADUSize++] = _u8MBSlave;
u8ModbusADU[u8ModbusADUSize++] = u8MBFunction;
switch(u8MBFunction)
{
case ku8MBReadCoils:
case ku8MBReadDiscreteInputs:
case ku8MBReadInputRegisters:
case ku8MBReadHoldingRegisters:
case ku8MBReadWriteMultipleRegisters:
u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadAddress);
u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadAddress);
u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadQty);
u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadQty);
break;
}
switch(u8MBFunction)
{
case ku8MBWriteSingleCoil:
case ku8MBMaskWriteRegister:
case ku8MBWriteMultipleCoils:
case ku8MBWriteSingleRegister:
case ku8MBWriteMultipleRegisters:
case ku8MBReadWriteMultipleRegisters:
u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteAddress);
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);
u8Qty = (_u16WriteQty % 8) ? ((_u16WriteQty >> 3) + 1) : (_u16WriteQty >> 3);
u8ModbusADU[u8ModbusADUSize++] = u8Qty;
for (i = 0; i < u8Qty; i++)
{
switch(i % 2)
{
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]);
u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[1]);
u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[1]);
break;
}
// append CRC
u16CRC = 0xFFFF;
for (i = 0; i < u8ModbusADUSize; i++)
{
u16CRC = _crc16_update(u16CRC, u8ModbusADU[i]);
}
u8ModbusADU[u8ModbusADUSize++] = lowByte(u16CRC);
u8ModbusADU[u8ModbusADUSize++] = highByte(u16CRC);
u8ModbusADU[u8ModbusADUSize] = 0;
// transmit request
if (_u8RTSMask) *_u8RTSPort |= _u8RTSMask; //Enable RTS Line if defined
for (i = 0; i < u8ModbusADUSize; i++)
{
MBSerial.write(u8ModbusADU[i]);
}
u8ModbusADUSize = 0;
MBSerial.flush();
//Fix for Serial.Flush() not waiting for buffer to clear. Hardcoded to Serial1
while (!(UCSR1A & (1 << UDRE1))) // Wait for empty transmit buffer
UCSR1A |= 1 << TXC1; // mark transmission not complete
while (!(UCSR1A & (1 << TXC1))); // Wait for the transmission to complete
if (_u8RTSMask) *_u8RTSPort &= ~_u8RTSMask; //Disable RTS Line if defined
// loop until we run out of time or bytes, or an error occurs
u32RXStartTime = millis();
while (millis() - u32RXStartTime < ku8MBResponseTimeout && u8BytesLeft && !u8MBStatus)
{
if (MBSerial.available())
{
u8ModbusADU[u8ModbusADUSize++] = MBSerial.read();
u8BytesLeft--;
}
// evaluate slave ID, function code once enough bytes have been read
if (u8ModbusADUSize == 5)
{
// verify response is for correct Modbus slave
if (u8ModbusADU[0] != _u8MBSlave)
{
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])
{
case ku8MBReadCoils:
case ku8MBReadDiscreteInputs:
case ku8MBReadInputRegisters:
case ku8MBReadHoldingRegisters:
case ku8MBReadWriteMultipleRegisters:
u8BytesLeft = u8ModbusADU[2];
break;
case ku8MBWriteSingleCoil:
case ku8MBWriteMultipleCoils:
case ku8MBWriteSingleRegister:
u8BytesLeft = 3;
break;
case ku8MBMaskWriteRegister:
u8BytesLeft = 5;
break;
}
}
if (u8ModbusADUSize == 6)
{
switch(u8ModbusADU[1])
{
case ku8MBWriteMultipleRegisters:
u8BytesLeft = u8ModbusADU[5];
break;
}
}
}
// verify response is large enough to inspect further
if (!u8MBStatus && (millis() - u32RXStartTime >= ku8MBResponseTimeout || u8ModbusADUSize < 5))
{
u8MBStatus = ku8MBResponseTimedOut;
}
// calculate CRC
u16CRC = 0xFFFF;
for (i = 0; i < (u8ModbusADUSize - 2); i++)
{
u16CRC = _crc16_update(u16CRC, u8ModbusADU[i]);
}
// verify CRC
if (!u8MBStatus && (lowByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 2] ||
highByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 1]))
{
u8MBStatus = ku8MBInvalidCRC;
}
// disassemble ADU into words
if (!u8MBStatus)
{
// evaluate returned Modbus function code
switch(u8ModbusADU[1])
{
case ku8MBReadCoils:
case ku8MBReadDiscreteInputs:
// load bytes into word; response bytes are ordered L, H, L, H, ...
for (i = 0; i < (u8ModbusADU[2] >> 1); i++)
{
if (i < ku8MaxBufferSize)
{
_u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 4], u8ModbusADU[2 * i + 3]);
}
}
// in the event of an odd number of bytes, load last byte into zero-padded word
if (u8ModbusADU[2] % 2)
{
if (i < ku8MaxBufferSize)
{
_u16ResponseBuffer[i] = word(0, u8ModbusADU[2 * i + 3]);
}
}
break;
case ku8MBReadInputRegisters:
case ku8MBReadHoldingRegisters:
case ku8MBReadWriteMultipleRegisters:
// load bytes into word; response bytes are ordered H, L, H, L, ...
for (i = 0; i < (u8ModbusADU[2] >> 1); i++)
{
if (i < ku8MaxBufferSize)
{
_u16ResponseBuffer[i] = word(u8ModbusADU[2 * i + 3], u8ModbusADU[2 * i + 4]);
}
}
break;
}
}
return u8MBStatus;
}