#include 'stm32f4xx.h'

// 定义结构体 typedef struct { GPIO_TypeDef* GPIOx; uint16_t GPIO_Pin; } GPIO_Config;

// 定义变量 GPIO_Config buzzer = {GPIOA, GPIO_Pin_0}; GPIO_Config led = {GPIOB, GPIO_Pin_0}; GPIO_Config button = {GPIOC, GPIO_Pin_13};

// 初始化蜂鸣器、LED、按键 void init() { RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOC, ENABLE);

GPIO_InitTypeDef GPIO_InitStructure;

// 蜂鸣器 GPIO_InitStructure.GPIO_Pin = buzzer.GPIO_Pin; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(buzzer.GPIOx, &GPIO_InitStructure);

// LED GPIO_InitStructure.GPIO_Pin = led.GPIO_Pin; GPIO_Init(led.GPIOx, &GPIO_InitStructure);

// 按键 GPIO_InitStructure.GPIO_Pin = button.GPIO_Pin; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(button.GPIOx, &GPIO_InitStructure); }

int main() { init();

while (1) { if (GPIO_ReadInputDataBit(button.GPIOx, button.GPIO_Pin) == Bit_RESET) { // 按键按下 GPIO_SetBits(buzzer.GPIOx, buzzer.GPIO_Pin); GPIO_SetBits(led.GPIOx, led.GPIO_Pin); // 延时 for (int i = 0; i < 1000000; i++) {} } else { // 按键松开 GPIO_ResetBits(buzzer.GPIOx, buzzer.GPIO_Pin); GPIO_ResetBits(led.GPIOx, led.GPIO_Pin); } } }

STM32 蜂鸣器和LED控制:按键触发,延时实现

原文地址: https://www.cveoy.top/t/topic/bts5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录