1.硬件
STM32单片机最小系统 LED灯模块 震动传感器模块
2.软件
exti驱动文件添加 GPIO常用函数 中断配置流程 main.c程序
# include "sys.h"
# include "delay.h"
# include "led.h"
# include "exti.h"
int main ( void )
{
HAL_Init ( ) ;
stm32_clock_init ( RCC_PLL_MUL9) ;
led_init ( ) ;
exti_init ( ) ;
while ( 1 )
{
if ( vibrate_flag_get ( ) == TRUE)
{
led1_on ( ) ;
delay_ms ( 2000 ) ;
led1_off ( ) ;
vibrate_flag_set ( FALSE) ;
}
}
}
# include "led.h"
# include "sys.h"
void led_init ( void )
{
GPIO_InitTypeDef gpio_initstruct;
__HAL_RCC_GPIOB_CLK_ENABLE ( ) ;
gpio_initstruct. Pin = GPIO_PIN_8 | GPIO_PIN_9;
gpio_initstruct. Mode = GPIO_MODE_OUTPUT_PP;
gpio_initstruct. Pull = GPIO_PULLUP;
gpio_initstruct. Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init ( GPIOB, & gpio_initstruct) ;
led1_off ( ) ;
led2_off ( ) ;
}
void led1_on ( void )
{
HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_8, GPIO_PIN_RESET) ;
}
void led1_off ( void )
{
HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_8, GPIO_PIN_SET) ;
}
void led1_toggle ( void )
{
HAL_GPIO_TogglePin ( GPIOB, GPIO_PIN_8) ;
}
void led2_on ( void )
{
HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_9, GPIO_PIN_RESET) ;
}
void led2_off ( void )
{
HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_9, GPIO_PIN_SET) ;
}
void led2_toggle ( void )
{
HAL_GPIO_TogglePin ( GPIOB, GPIO_PIN_9) ;
}
# ifndef __LED_H__
# define __LED_H__
void led_init ( void ) ;
void led1_on ( void ) ;
void led1_off ( void ) ;
void led1_toggle ( void ) ;
void led2_on ( void ) ;
void led2_off ( void ) ;
void led2_toggle ( void ) ;
# endif
# include "exti.h"
# include "sys.h"
# include "delay.h"
# include "led.h"
uint8_t vibrate_flag = FALSE;
void exti_init ( void )
{
GPIO_InitTypeDef gpio_initstruct;
__HAL_RCC_GPIOA_CLK_ENABLE ( ) ;
gpio_initstruct. Pin = GPIO_PIN_4;
gpio_initstruct. Mode = GPIO_MODE_IT_FALLING;
gpio_initstruct. Pull = GPIO_PULLUP;
HAL_GPIO_Init ( GPIOA, & gpio_initstruct) ;
HAL_NVIC_SetPriority ( EXTI4_IRQn, 2 , 0 ) ;
HAL_NVIC_EnableIRQ ( EXTI4_IRQn) ;
}
void EXTI4_IRQHandler ( void )
{
HAL_GPIO_EXTI_IRQHandler ( GPIO_PIN_4) ;
}
void HAL_GPIO_EXTI_Callback ( uint16_t GPIO_Pin)
{
if ( GPIO_Pin == GPIO_PIN_4)
{
if ( HAL_GPIO_ReadPin ( GPIOA, GPIO_PIN_4) == GPIO_PIN_RESET)
vibrate_flag = TRUE;
}
}
uint8_t vibrate_flag_get ( void )
{
uint8_t temp = vibrate_flag;
vibrate_flag = FALSE;
return temp;
}
void vibrate_flag_set ( uint8_t value)
{
vibrate_flag = value;
}
# ifndef __EXTI_H__
# define __EXTI_H__
# include "stdint.h"
# define TRUE 1
# define FALSE 0
void exti_init ( void ) ;
uint8_t vibrate_flag_get ( void ) ;
void vibrate_flag_set ( uint8_t value) ;
# endif
3.实物效果
硬件模块接线 LED1正—>VCC(3.3V) LED1负—>PB8 震动传感器I/O—>PA4 震动传感器VCC—>3.3V或5V(3.3V) 震动传感器GND—>GND ST-Link下载方式实验现象 使用中断的方法,振动传感器检测到振动时,LED1 点亮 2 秒,之后熄灭。