0

一开始,我对微控制器编程的世界还比较陌生

我在另一个回调函数 (HAL_UART_RxCpltCallback) 中调用 HAL_UART_Transmit_IT 时遇到问题。我想编写一个简单的程序,它将从 UART 读取信息,然后以未更改的形式(回显)将其写出。“轮询模式”下的功能 - HAL_UART_Transmit() - 效果很好,但我想在中断上完成所有功能。

#include "stm32f3xx_hal.h"
#include "stm32f303xe.h"
#include "main.h"
#include <string.h>

void SystemClockConfig(void);
void UART2_Init(void);
void Error_handler (void);
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);

UART_HandleTypeDef huart2;

char *myUserData = "*** Communication Starts ***\n\r";
uint8_t data_buffer[100];
uint32_t count = 0;
uint8_t rcvd_data;

int main (void)
{
    HAL_Init();
    SystemClockConfig();
    UART2_Init();

    if(HAL_UART_Transmit(&huart2, (uint8_t*)myUserData, strlen(myUserData), HAL_MAX_DELAY) != HAL_OK)
    {
        Error_handler();
    }

    HAL_UART_Receive_IT(&huart2, &rcvd_data,1); // receive message from UART
    while(1)
    {
        // it works ok
        HAL_UART_Transmit_IT(&huart2, (uint8_t*)myUserData, strlen(myUserData));
        HAL_Delay(5000);
    }

    return 0;
}

void UART2_Init(void)
{
    huart2.Instance = USART2;
    huart2.Init.BaudRate = 115200 ;
    huart2.Init.WordLength = UART_WORDLENGTH_8B;
    huart2.Init.StopBits = UART_STOPBITS_1;
    huart2.Init.Parity = UART_PARITY_NONE;
    huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart2.Init.Mode = UART_MODE_TX_RX;
    if (HAL_UART_Init(&huart2) != HAL_OK)
    {
        Error_handler();
    }
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(rcvd_data == '\r')
    {
        data_buffer[count++]='\r';
        HAL_UART_Transmit_IT(huart, data_buffer, count); // here is a problem. HAL_UART_TRANSMIT() works ok
            // clear array for next incoming message.
            // whether it is the right place for such an operation?
            for (int i=0; i<sizeof(data_buffer);++i)
            {
                data_buffer[i] = 0;
            }

    } else {
    data_buffer[count++] = rcvd_data;
    }
    HAL_UART_Receive_IT(&huart2, &rcvd_data,1); // receive next byte

}

void SystemClockConfig(void)
{
// Do Nothing
}

void Error_handler (void)
{
    while(1);
}

还有,我想问一下,在回调函数中清理数组是一个好的解决方案还是应该以不同的方式解决?

4

0 回答 0