测试记录-stm32串口收发

#include "main.h"
#include "stm32f0xx_hal.h"
#include <stdio.h>
#include <string.h>

UART_HandleTypeDef huart1;

volatile char rx_buffer[256];
volatile uint16_t rx_index = 0;
volatile uint8_t rx_complete = 0;

// LED状态枚举
typedef enum {
    LED_OFF,
    LED_ON,
    LED_FLASH
} LED_State;

LED_State led_state = LED_OFF;
int led_flash_interval = 1000; // 默认LED闪烁间隔为1000ms
int led_brightness = 5; // 默认LED亮度为5

void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
void process_command(const char *command);

int main(void)
{
    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();
    MX_USART1_UART_Init();

    HAL_UART_Receive_IT(&huart1, (uint8_t *)rx_buffer, 1); // 启动中断接收

    while (1)
    {
        if (rx_complete)
        {
            printf("Received data: %s\n", rx_buffer);
            process_command(rx_buffer);

            // 处理完成后重置接收完成标志
            rx_complete = 0;

            // 重新启动接收
            HAL_UART_Receive_IT(&huart1, (uint8_t *)rx_buffer, 1);
        }
    }
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)
    {
        if (rx_buffer[rx_index] == '\n')
        {
            rx_buffer[rx_index] = '\0'; // 添加字符串结束符
            rx_complete = 1;            // 设置接收完成标志
            rx_index = 0;               // 重置接收缓冲区索引
        }
        else
        {
            rx_index++;
            // 如果缓冲区溢出,重置索引
            if (rx_index >= sizeof(rx_buffer))
            {
                rx_index = 0;
            }
        }
        HAL_UART_Receive_IT(&huart1, (uint8_t *)&rx_buffer[rx_index], 1); // 继续中断接收
    }
}

void process_command(const char *command)
{
    // 提取命令
    char *token = strtok((char *)command, " ");
    if (token == NULL)
    {
        return; // 无效命令
    }

    // 比较命令并执行相应操作
    if (strcmp(token, "ledon") == 0)
    {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET); // 点亮LED
        led_state = LED_ON;
    }
    else if (strcmp(token, "ledoff") == 0)
    {
        HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET); // 熄灭LED
        led_state = LED_OFF;
    }
    else if (strcmp(token, "ledflash") == 0)
    {
        token = strtok(NULL, " ");
        if (token != NULL)
        {
            led_flash_interval = atoi(token); // 更新LED闪烁间隔
            led_state = LED_FLASH;
        }
    }
    else if (strcmp(token, "ledlight") == 0)
    {
        token = strtok(NULL, " ");
        if (token != NULL)
        {
            led_brightness = atoi(token); // 更新LED亮度
            // 在这里可以根据亮度控制LED的 PWM 输出等
        }
    }
    else
    {
        // 未知命令
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值