You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

  1. Match Data Types: sizeof(counter) sends all bytes of your integer (e.g., 4 bytes for a 32-bit uint32_t or int). Note the data type of counter—you'll need this to configure Simulink correctly.
  2. 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.
  3. Simulink Setup:
    • Use the Serial Receive module in your model.
    • Set its "Data type" to match the counter type in your code (e.g., uint32 if counter is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:03:12