
按键控制LED灯亮灭我这里直接用A0,A1,A4,A6口了省得麻烦。主函数#include stm32f10x.h // Device header void led_initial(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_ModeGPIO_Mode_Out_PP; GPIO_InitStruct.GPIO_PinGPIO_Pin_0|GPIO_Pin_1; GPIO_InitStruct.GPIO_SpeedGPIO_Speed_50MHz; GPIO_Init(GPIOA,GPIO_InitStruct); GPIO_SetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1); } void control_led(uint16_t GPIO_Pin_x,uint8_t key) { if(key0) { GPIO_SetBits(GPIOA,GPIO_Pin_x); } else { GPIO_ResetBits(GPIOA,GPIO_Pin_x); } }key.c文件#include stm32f10x.h // Device header #include Delay.h void key_initial(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_ModeGPIO_Mode_IPU; GPIO_InitStruct.GPIO_PinGPIO_Pin_4|GPIO_Pin_6; GPIO_InitStruct.GPIO_SpeedGPIO_Speed_50MHz; GPIO_Init(GPIOA,GPIO_InitStruct); } uint8_t presskey(GPIO_TypeDef*GPIOx,uint16_t GPIO_Pin) { uint8_t num0; if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin)0) { Delay_ms(20); while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin)0); Delay_ms(20); num1; } return num; }led.c文件#include stm32f10x.h // Device header void led_initial(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_ModeGPIO_Mode_Out_PP; GPIO_InitStruct.GPIO_PinGPIO_Pin_0|GPIO_Pin_1; GPIO_InitStruct.GPIO_SpeedGPIO_Speed_50MHz; GPIO_Init(GPIOA,GPIO_InitStruct); GPIO_SetBits(GPIOA,GPIO_Pin_0|GPIO_Pin_1); } void control_led(uint16_t GPIO_Pin_x,uint8_t key) { if(key0) { GPIO_SetBits(GPIOA,GPIO_Pin_x); } else { GPIO_ResetBits(GPIOA,GPIO_Pin_x); } }光敏传感器控制控制有源蜂鸣器有光响无光不响主函数#include stm32f10x.h // Device header #include Delay.h #include LightSensor.h #include Buzzer.h int main(void) { LightSensorInit(); BuzzerInit(); while(1) { BuzzerControl(GetLight()); } }Buzzer驱动函数#include stm32f10x.h // Device header void BuzzerInit(void)//低电平触发 { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_ModeGPIO_Mode_Out_PP; GPIO_InitStruct.GPIO_PinGPIO_Pin_0; GPIO_InitStruct.GPIO_SpeedGPIO_Speed_50MHz; GPIO_Init(GPIOA,GPIO_InitStruct); GPIO_SetBits(GPIOA,GPIO_Pin_0); } void BuzzerControl(uint8_t num) { if(num1) { GPIO_ResetBits(GPIOA,GPIO_Pin_0); } else { GPIO_SetBits(GPIOA,GPIO_Pin_0); } }光敏传感器驱动函数#include stm32f10x.h // Device header void LightSensorInit(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_ModeGPIO_Mode_IPD; GPIO_InitStruct.GPIO_PinGPIO_Pin_2; GPIO_InitStruct.GPIO_SpeedGPIO_Speed_50MHz; GPIO_Init(GPIOA,GPIO_InitStruct); } uint8_t GetLight(void) { if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_2)0)//有光光敏传感器输出0 return 1; else return 0; }HAL库按键控制板载LED亮灭while (1) { /* USER CODE END WHILE */ if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_1)1) HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_SET); else HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,GPIO_PIN_RESET); /* USER CODE BEGIN 3 */ }