stm32串口显示按键值
时间: 2023-11-19 15:05:47 浏览: 57
以下是STM32串口显示按键值的示例代码:
```
#include "stm32f10x.h"
#include <stdio.h>
// 定义按键和LED的引脚
#define KEY_PIN GPIO_Pin_0
#define KEY_GPIO_PORT GPIOA
#define KEY_GPIO_CLK RCC_APB2Periph_GPIOA
#define LED_PIN GPIO_Pin_1
#define LED_GPIO_PORT GPIOA
#define LED_GPIO_CLK RCC_APB2Periph_GPIOA
// 定义串口参数
#define USARTx USART1
#define USARTx_CLK RCC_APB2Periph_USART1
#define USARTx_GPIO_CLK RCC_APB2Periph_GPIOA
#define USARTx_TX_PIN GPIO_Pin_9
#define USARTx_TX_GPIO_PORT GPIOA
#define USARTx_RX_PIN GPIO_Pin_10
#define USARTx_RX_GPIO_PORT GPIOA
#define USARTx_IRQn USART1_IRQn
// 定义变量
uint8_t key_value;
// 函数声明
void GPIO_Config(void);
void USART_Config(void);
int main(void)
{
GPIO_Config();
USART_Config();
printf("STM32 USART Key Value Test\r\n");
while (1)
{
// 检测按键状态
if (GPIO_ReadInputDataBit(KEY_GPIO_PORT, KEY_PIN) == 0)
{
// 按键按下,点亮LED
GPIO_SetBits(LED_GPIO_PORT, LED_PIN);
key_value = 1;
printf("Key Value: %d\r\n", key_value);
}
else
{
// 按键释放,熄灭LED
GPIO_ResetBits(LED_GPIO_PORT, LED_PIN);
key_value = 0;
}
// 稍微延时一下,避免按键抖动
for (int i = 0; i < 100000; i++);
}
}
// 配置GPIO
void GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
// 打开GPIO时钟
RCC_APB2PeriphClockCmd(KEY_GPIO_CLK | LED_GPIO_CLK, ENABLE);
// 配置按键引脚为输入模式
GPIO_InitStructure.GPIO_Pin = KEY_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(KEY_GPIO_PORT, &GPIO_InitStructure);
// 配置LED引脚为输出模式
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
}
// 配置USART
void USART_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
// 打开USART时钟和GPIO时钟
RCC_APB2PeriphClockCmd(USARTx_CLK | USARTx_GPIO_CLK, ENABLE);
// 配置USART引脚
GPIO_InitStructure.GPIO_Pin = USARTx_TX_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = USARTx_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStructure);
// 配置USART参数
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);
}
```
该代码实现了通过串口显示按键值。按键按下时,点亮LED并将按键值设为1,同时通过串口输出按键值;按键释放时,熄灭LED并将按键值设为0。在主循环中添加了一个简单的延时以避免按键抖动。