@@ -39,18 +39,23 @@ Modbus::Modbus(uint8_t _unitID, int _ctrlPin) {
39
39
*
40
40
* @param boud the serial port boud rate.
41
41
*/
42
- void Modbus::begin (int boud) {
42
+ void Modbus::begin (unsigned long boud) {
43
43
// set control pin
44
44
if (ctrlPin) {
45
45
pinMode (ctrlPin, OUTPUT);
46
46
}
47
47
48
48
// open port and set the timeout for 3.5 chars.
49
49
Serial.begin (boud);
50
- Serial.flush ( );
50
+ Serial.setTimeout ( 0 );
51
51
52
- // set the T35 interframe timout to 5 milliseconds.
53
- timeout = 5 ;
52
+ // set the T35 interframe timeout
53
+ if (boud > 19200 ) {
54
+ timeout = 1750 ;
55
+ }
56
+ else {
57
+ timeout = 35000000 / boud; // 1T * 3.5 = T3.5
58
+ }
54
59
55
60
// init last received values
56
61
last_receive_len = 0 ;
@@ -86,20 +91,6 @@ uint16_t Modbus::calcCRC(uint8_t *buf, int length) {
86
91
return crc;
87
92
}
88
93
89
- /* *
90
- * Read all bytes available in serial port.
91
- */
92
- int serialRead (uint8_t *buffer, uint8_t len) {
93
- uint8_t size = 0 ;
94
-
95
- while (Serial.available () && size < len) {
96
- buffer[size] = Serial.read ();
97
- size++;
98
- }
99
-
100
- return size;
101
- }
102
-
103
94
/* *
104
95
* wait for end of frame, parse request and answer it.
105
96
*/
@@ -123,18 +114,18 @@ int Modbus::poll() {
123
114
// if we have new data, update last received time and length.
124
115
if (available_len != last_receive_len) {
125
116
last_receive_len = available_len;
126
- last_receive_time = millis ();
117
+ last_receive_time = micros ();
127
118
128
119
return 0 ;
129
120
}
130
121
131
- // if no new data, wait for T35 milliseconds .
132
- if (millis () < (last_receive_time + timeout)) {
122
+ // if no new data, wait for T35 microseconds .
123
+ if (micros () < (last_receive_time + timeout)) {
133
124
return 0 ;
134
125
}
135
126
136
127
// we waited for the inter-frame timeout, read the frame.
137
- lengthIn = serialRead (bufIn, MAX_BUFFER);
128
+ lengthIn = Serial. readBytes (bufIn, MAX_BUFFER);
138
129
last_receive_len = 0 ;
139
130
last_receive_time = 0 ;
140
131
} else {
@@ -267,18 +258,16 @@ int Modbus::poll() {
267
258
// send buffer
268
259
Serial.write (bufOut, lengthOut);
269
260
270
- // wait until serial port register (UCSRnA)
271
- // transfer complete bit (TXCn) is on
272
- // and then set rs485 control pin to read
261
+ // wait for the transmission of outgoing data
262
+ // to complete and then set rs485 control pin to read
273
263
// [ on SoftwareSerial use delay ? ]
274
- while (!(UCSR0A & ( 1 << TXC0)) );
264
+ Serial. flush ( );
275
265
digitalWrite (ctrlPin, LOW);
276
266
} else {
277
267
// just send the buffer.
278
268
Serial.write (bufOut, lengthOut);
279
269
}
280
270
281
- Serial.flush ();
282
271
return lengthOut;
283
272
}
284
273
0 commit comments