STM32 con un MAX3485 recibe mi propio eco y pierde el inicio de la respuesta Modbus
Traducido del English por IA ·
Catorce años en el lado de los PLC, es la primera vez que hago Modbus RTU desde un microcontrolador sin más, así que el protocolo no es el problema, lo es el lado del MCU.Hardware: STM32F103 (Blue Pill), USART2, MAX3485, DE y /RE unidos en PA8. Leo un medidor de caudal magnético, 9600 8N1, esclavo 7, registros de retención 0x0010 a 0x0013. Más adelante, un ESP32 junto a él enviará los valores a Hermetry, pero primero necesito lecturas limpias.En el osciloscopio mi petición se ve correcta y el medidor responde, puedo ver su respuesta en A/B. Lo que recibe mi código es incorrecto. Normalmente faltan los dos o tres primeros bytes de la respuesta. A veces recibo en el búfer mi propia petición antes de la respuesta. Código, simplificado:
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET); // DE on
HAL_UART_Transmit(&huart2, req, 8, 100);
HAL_Delay(5);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET); // DE off, RE on
HAL_UART_Receive(&huart2, rx, 9, 200);
Fourteen years on the PLC side, first time doing Modbus RTU from a bare microcontroller, so the protocol is not the problem, the MCU side is.
Hardware: STM32F103 (Blue Pill), USART2, MAX3485, DE and /RE tied together on PA8. Reading a magnetic flow meter, 9600 8N1, slave 7, holding registers 0x0010 to 0x0013. Later an ESP32 next to it will send the values to Hermetry, but first I need clean reads.
On the scope my request looks correct and the meter answers, I can see its reply on A/B. What my code receives is wrong. Usually the first two or three bytes of the reply are missing. Sometimes I get my own request back in the buffer before the reply. Code, simplified:
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET); // DE on
HAL_UART_Transmit(&huart2, req, 8, 100);
HAL_Delay(5);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET); // DE off, RE on
HAL_UART_Receive(&huart2, rx, 9, 200);
Traducido del English por IA ·
¿Probaste intercambiar A y B?
Did you try swapping A and B?
Traducido del English por IA ·
¿Quizás una diferencia de velocidad en baudios entre los dos?
Maybe a baud rate mismatch between the two?
Traducido del English por IA ·
Ninguna de las dos, la petición se decodifica bien en el osciloscopio y el medidor responde a ella. El problema está en mi lado.
Neither, the request decodes fine on the scope and the meter replies to it. It’s my side.
Traducido del English por IA ·
El problema está en el timing alrededor de DE; yo tuve exactamente lo mismo en un banco de pruebas con un F103.HAL_UART_Transmit retorna cuando el último byte ha entrado en el registro de datos, no cuando ha salido del registro de desplazamiento. Además, esperas 5 ms encima. A 9600 baudios, un byte dura unos 1 ms, y un medidor rápido empieza a responder en pocos ms. Mientras DE está en alto, /RE también está en alto, así que el receptor está apagado y se pierden los primeros bytes de la respuesta. Y como HAL_UART_Receive solo se llama después, lo que llegue entretanto se pierde o queda a medias en el registro de datos.El eco viene del orden contrario: si la recepción ya está activa mientras transmites y /RE baja un momento, lees de vuelta tu propia petición.Suelta DE en cuanto se active el flag de transmisión completa (TC) y activa la recepción justo después:
__HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_TC);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
HAL_UART_Transmit(&huart2, req, 8, 100);
while (!__HAL_UART_GET_FLAG(&huart2, UART_FLAG_TC)) {}
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET);
__HAL_UART_FLUSH_DRREGISTER(&huart2);
HAL_UART_Receive(&huart2, rx, 9, 200);
Mejor aún, usa recepción por interrupción o DMA con la interrupción de línea inactiva (idle line): entonces una pausa de 3,5 caracteres cierra la trama y no necesitas conocer la longitud de antemano. El F103 no tiene pin DE por hardware para RS-485; las familias más nuevas sí lo tienen, lo que evita todo esto.
It’s the timing around DE, I had the exact same thing on a lab rig with an F103.
HAL_UART_Transmit returns when the last byte has gone into the data register, not when it has left the shift register. Then you wait 5 ms on top. At 9600 one byte is about 1 ms, and a fast meter starts answering within a few ms. While DE is high, /RE is high too, so the receiver is off and the first bytes of the reply are gone. And because HAL_UART_Receive is only called after that, anything that came in meanwhile is lost or sits half in the data register.
The echo comes from the other order: if the receive is already armed while you transmit and /RE is low for a moment, you read back your own request.
Drop DE the moment the transmit complete flag (TC) is set, and arm the receive right after:
__HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_TC);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
HAL_UART_Transmit(&huart2, req, 8, 100);
while (!__HAL_UART_GET_FLAG(&huart2, UART_FLAG_TC)) {}
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET);
__HAL_UART_FLUSH_DRREGISTER(&huart2);
HAL_UART_Receive(&huart2, rx, 9, 200);
Better still, use interrupt or DMA receive with the idle line interrupt, then a 3.5 character gap ends the frame and you don’t need to know the length in advance. The F103 has no hardware DE pin for RS-485, newer families do, which saves all of this.
Traducido del English por IA ·
Eso era. El HAL_Delay(5) lo había añadido probando a ciegas; quitarlo y esperar a TC me da los 9 bytes completos y el CRC cuadra siempre. Tampoco hay más eco. Ahora paso a DMA con idle line, como sugirió Aoife.
That was it. The HAL_Delay(5) was something I’d added while guessing, removing it and waiting on TC gives me all 9 bytes and the CRC checks out every time. No more echo either. Moving to idle line DMA next like Aoife suggested.
- Debes estar registrado para responder a este debate.
Únete a la conversación
Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

