如何通过UART发送计数器变量值至Matlab Simulink并实现正确可视化
Looks like you're sending formatted string output via printf right now, which is why Simulink is picking up ASCII values instead of the raw counter number. Let's fix this by sending the binary representation of your counter variable directly over UART, which Simulink can parse correctly as a numeric value.
The Problem with Your Current Code
When you use printf("The actual counter value is: %d \r\n", counter);, you're converting the integer counter into a human-readable string. For example, if counter=5, this sends ASCII characters like 'T', 'h', 'e', ..., '5' over UART. Simulink is receiving each of these characters as their individual ASCII codes, which isn't what you want for numeric visualization.
The Fix: Send Raw Binary Data Instead
Replace the printf call with a direct UART transmission of the counter variable's bytes. Here's your updated loop code:
while(1){ HAL_UART_Receive_IT(&huart2, &bufferRX, 1); //Serial Stream Routine if(streamActive == 1 && counter < MAX_VALUE) //RUNNING state: we start the counter and the transmission begin { if (dataReady == 1) { // Send the raw binary bytes of the counter variable HAL_UART_Transmit(&huart2, (uint8_t*)&counter, sizeof(counter), HAL_MAX_DELAY); counter++; dataReady = 0; } } else if(streamActive == 1 && counter >= MAX_VALUE){ counter = 0; } }
Key Details to Get This Working
- Match Data Types:
sizeof(counter)sends all bytes of your integer (e.g., 4 bytes for a 32-bituint32_torint). Note the data type ofcounter—you'll need this to configure Simulink correctly. - Byte Order: Most MCUs (like STM32) use little-endian byte order. In Simulink's Serial Receive module, set the "Byte Order" to Little-Endian to match your hardware.
- Simulink Setup:
- Use the Serial Receive module in your model.
- Set its "Data type" to match the
countertype in your code (e.g.,uint32ifcounteris an unsigned 32-bit integer). - Configure baud rate, parity, stop bits to match your UART settings.
- Set "Number of data points" to 1 to receive one counter value per transmission.
Your Existing UART Functions
Your HAL_UART_RxCpltCallback and __io_putchar functions don't need changes unless you no longer use printf for debugging. If you still need printf elsewhere, keep __io_putchar—this fix only replaces the counter transmission logic.
内容的提问来源于stack exchange,提问作者Giulio

