通过串口输入控制LED灯亮灭

if(HAL_UART_Receive(&huart1,&byte,1,100)==HAL_OK)
		{
		  if(byte=='\n')
			{
				if(strncmp(buf,"ON",2)==0)
				{
					HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_RESET);
				}else if(strncmp(buf,"OFF",3)==0)
				{
					HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0,GPIO_PIN_SET);
				}
			  HAL_UART_Transmit(&huart1,buf,strlen(buf),100);
			  memset(buf,0,sizeof(buf));
				len=0;
			}
			else
			{
			 buf[len++]=byte;
			}
		}

  

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题涉及到硬件和软件两个方面,下面我会分别介绍。 **硬件部分:** 首先,你需要准备以下硬件: 1. STM32开发板(我以STM32F103C8T6为例) 2. LED灯(可以选用任意颜色) 3. 杜邦线若干条 4. USB转串口模块(用于将开发板连接到计算机) 接下来,按照以下步骤进行连接: 1. 将LED的正极连接到开发板的PB12引脚,将LED的负极连接到GND引脚。 2. 将USB转串口模块的TX引脚连接到开发板的RX引脚,将USB转串口模块的RX引脚连接到开发板的TX引脚。 3. 将USB转串口模块的GND引脚连接到开发板的GND引脚。 4. 将USB转串口模块连接到计算机,并确定其对应的串口号。 **软件部分:** 以下是程序代码: ```c #include "stm32f10x.h" #include "stdio.h" void USART1_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, &USART_InitStructure); USART_Cmd(USART1, ENABLE); } void LED_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); } void USART1_SendChar(uint8_t ch) { while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); USART_SendData(USART1, ch); } int main(void) { USART1_Init(); LED_Init(); while(1) { if(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == SET) { uint8_t ch = USART_ReceiveData(USART1); if(ch == '1') { GPIO_SetBits(GPIOB, GPIO_Pin_12); USART1_SendChar('L'); } else if(ch == '0') { GPIO_ResetBits(GPIOB, GPIO_Pin_12); USART1_SendChar('H'); } } } } ``` 代码中使用串口1和PA9、PA10引脚进行通信,LED灯对应的GPIO引脚为PB12。 在代码中,当从串口接收到字符 '1' 时,将LED灯亮起,并通过串口发送字符 'L';当从串口接收到字符 '0' 时,将LED灯熄,并通过串口发送字符 'H'。 在Proteus中,需要添加STM32开发板和串口调试助手模块,并进行连接。在串口调试助手中输入字符 '1' 或 '0',即可控制LED的亮。 以上就是控制STM32串口控制LED灯亮并用Proteus仿真结果的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值