#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
{
// 未知命令
}
}