二、按键计数STM32单片机外接扩展板D2、D3接开关S2和S3,编程实现对按键进行循环加、减计数00-59。S1实现加1,S2实现减1,每次按下按键,计得当前值在串口上面显示。
时间: 2023-06-24 22:08:03 浏览: 100
以下是一个简单的实现,通过轮询检测按键状态,每次按下按键后对计数器进行加减操作,并将当前值通过串口发送出去:
```c
#include "stm32f10x.h"
#include "stdio.h"
#define S1_GPIO GPIOA // S1对应的GPIO
#define S2_GPIO GPIOA // S2对应的GPIO
#define S1_PIN GPIO_Pin_0 // S1对应的Pin
#define S2_PIN GPIO_Pin_1 // S2对应的Pin
#define LED_GPIO GPIOB // LED对应的GPIO
#define LED_PIN GPIO_Pin_0 // LED对应的Pin
void USART1_Init(void) {
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, 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_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
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(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void GPIO_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = S1_PIN | S2_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
int main(void) {
int count = 0;
int last_s1_state = 1;
int last_s2_state = 1;
GPIO_Init();
USART1_Init();
while (1) {
int s1_state = GPIO_ReadInputDataBit(S1_GPIO, S1_PIN);
int s2_state = GPIO_ReadInputDataBit(S2_GPIO, S2_PIN);
if (s1_state == 0 && last_s1_state == 1) {
count = (count + 1) % 60;
printf("Count: %d\n", count);
}
if (s2_state == 0 && last_s2_state == 1) {
count = (count + 59) % 60;
printf("Count: %d\n", count);
}
last_s1_state = s1_state;
last_s2_state = s2_state;
GPIO_WriteBit(LED_GPIO, LED_PIN, count % 2 == 0 ? Bit_RESET : Bit_SET);
}
}
```
在代码中,我们首先定义了按键和 LED 对应的 GPIO 和 Pin,然后编写了串口初始化和 GPIO 初始化的函数。在 `main` 函数中,我们定义了一个计数器 `count`,以及记录上一次按键状态的变量 `last_s1_state` 和 `last_s2_state`。在主循环中,我们不断轮询检测按键的状态,并在按下按键时对计数器进行加减操作,并通过串口将当前计数值发送出去。同时,我们也将计数器的奇偶性映射到 LED 的亮灭上,以便观察计数器的变化。
阅读全文