STM32F1用串口和光敏控制LED灯代码和接线图
时间: 2024-06-03 12:08:50 浏览: 72
接线图:
![image](https://user-images.githubusercontent.com/55309181/131206139-2f2b33d0-0d40-4f39-bc25-34b0c8c8bca7.png)
代码:
```c
#include "stm32f10x.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define LED_Pin GPIO_Pin_13
#define LED_Port GPIOC
#define USARTx USART1
void GPIO_Configuration(void);
void USART_Configuration(void);
void USART_SendString(USART_TypeDef* USARTx, char* str);
int main(void)
{
GPIO_Configuration();
USART_Configuration();
while(1)
{
if(USART_GetFlagStatus(USARTx, USART_FLAG_RXNE) == SET)
{
char ch = USART_ReceiveData(USARTx);
if(ch == 'L') //当收到字符'L'时,点亮LED灯
{
GPIO_SetBits(LED_Port, LED_Pin);
USART_SendString(USARTx, "LED ON\r\n");
}
else if(ch == 'D') //当收到字符'D'时,熄灭LED灯
{
GPIO_ResetBits(LED_Port, LED_Pin);
USART_SendString(USARTx, "LED OFF\r\n");
}
}
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_Pin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_Port, &GPIO_InitStructure);
}
void USART_Configuration(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 = 9600;
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(USARTx, &USART_InitStructure);
USART_Cmd(USARTx, ENABLE);
}
void USART_SendString(USART_TypeDef* USARTx, char* str)
{
while(*str)
{
while(USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
USART_SendData(USARTx, *str++);
}
}
```
阅读全文