如何修改UART转Telnet代码提取Modbus十六进制帧特定字段?
UART to Telnet Forwarding + Modbus Specific Field Extraction Solution
Hey there, let's break down how to solve both your UART forwarding task and Modbus data extraction need clearly:
1. Complete the UART-to-Telnet Forwarding Code
Your existing code was missing some critical pieces (like handling new client connections and proper bracket closure). Here's the polished, functional version:
// Pre-defined variables (adjust these based on your hardware setup) HardwareSerial mySerial(1); // Use Serial1/Serial2 depending on your board WiFiServer telnetServer(23); // Telnet default port is 23 const int MAX_TELNET_CLIENTS = 4; // Max simultaneous clients you want to support WiFiClient telnetClients[MAX_TELNET_CLIENTS]; void setup() { Serial.begin(115200); mySerial.begin(9600); // Match your UART device's baud rate telnetServer.begin(); } void loop() { // Handle new Telnet client connections first WiFiClient newClient = telnetServer.available(); if (newClient) { bool clientAdded = false; for (int i = 0; i < MAX_TELNET_CLIENTS; i++) { if (!telnetClients[i] || !telnetClients[i].connected()) { if (telnetClients[i]) telnetClients[i].stop(); telnetClients[i] = newClient; Serial.print("New Telnet client from: "); Serial.println(newClient.remoteIP()); clientAdded = true; break; } } if (!clientAdded) { newClient.println("Maximum clients reached. Try later."); newClient.stop(); } } // Read UART data and forward to all connected Telnet clients if (mySerial.available()) { size_t dataLen = mySerial.available(); uint8_t uartBuffer[dataLen]; mySerial.readBytes(uartBuffer, dataLen); // Forward to each active client for (int i = 0; i < MAX_TELNET_CLIENTS; i++) { if (telnetClients[i] && telnetClients[i].connected()) { telnetClients[i].write(uartBuffer, dataLen); delay(1); // Small delay to prevent data loss on client side } } } }
Key Improvements:
- Added full client connection management (accept new clients, replace disconnected ones, handle max client limit)
- Fixed variable scoping and bracket closure issues from your original snippet
- Made the code more readable with descriptive variable names
2. Extract the 4th and 5th Hex Pairs from Modbus Data
Your target Modbus frame is 10 03 02 01 1F 04 1F — remember that byte arrays are 0-indexed, so:
- 4th hex pair (
01) = index 3 in the byte array - 5th hex pair (
1F) = index 4 in the byte array
Here's how to extract and use these values, integrated right into the UART forwarding logic:
// Insert this inside the UART data handling block (after reading uartBuffer) if (dataLen >= 5) { // Ensure we have at least 5 bytes to avoid index out of bounds uint8_t fourthHexByte = uartBuffer[3]; // 0x01 uint8_t fifthHexByte = uartBuffer[4]; // 0x1F // Optional: Combine into a 16-bit value (since Modbus uses big-endian) uint16_t combinedValue = (fourthHexByte << 8) | fifthHexByte; // 0x011F = 287 in decimal // Example usage: Print the extracted values Serial.print("Extracted 4th hex byte: 0x"); Serial.println(fourthHexByte, HEX); Serial.print("Extracted 5th hex byte: 0x"); Serial.println(fifthHexByte, HEX); Serial.print("Combined 16-bit value: 0x"); Serial.println(combinedValue, HEX); }
Notes:
- Always check the data length first to prevent crashes from accessing invalid array indices
- The combined value uses left shift (
<< 8) to move the 4th byte into the high 8 bits, then combines with the 5th byte using bitwise OR (|) — this matches Modbus's big-endian byte order - You can modify the usage logic to send just this extracted value to Telnet clients, store it, or use it for further processing
内容的提问来源于stack exchange,提问作者dadex
相关产品推荐
相关产品推荐

