原理:

  注意:这里使用迷你版,其他版本IO口设置不同,详细请查询原理图   微信图片_20201231120930   由图可知:LED0是PA8,LED1是PD2,且都是共阳极,高电平灭,低电平亮 所以只需要控制这两个IO口的电平就能实现LED灯的闪烁了。   GPIO口设置前要先进行时钟的使能!!! (外设,包括GPIO使用前都要先使能相应的时钟!!)   同时设置为推挽输出(可以准确输出高低电平) 还要设置输出速度。   由于STM32都是使用相应的底层,所以要记住以下几个函数:  
  • 1个初始化函数
 
void GPIO_Init(GPIO_TypeDef* GPIOx, GPIO_InitTypeDef* GPIO_InitStruct);
 
  • 2个读取输入电平函数
 
uint8_t GPIO_ReadInputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
uint16_t GPIO_ReadInputData(GPIO_TypeDef* GPIOx);
 
  • 4个设置输出电平函数
 
void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void GPIO_ResetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void GPIO_WriteBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, BitAction BitVal);
void GPIO_Write(GPIO_TypeDef* GPIOx, uint16_t PortVal);
 

主要代码:

  main.c  
******************************************************************************
* 文件名:LED灯
* 描  述:L1,L2每隔500ms闪烁一次
* 作  者:思索与猫
* 日  期: 19/4/1
* 备  注: 
*         
******************************************************************************
#include "stm32f10x.h"                  // Device header
#include "led.h"
#include "delay.h"

int main()
{
		delay_init();        //延时函数初始化
		LED_Init();		     //LED灯初始化
		while(1)
		{
				GPIO_SetBits(GPIOA,GPIO_Pin_8);      //PA8,PD2高电平,L0,L1灭
				GPIO_SetBits(GPIOD,GPIO_Pin_2);
//下方代码为更简单的对位操作IO口,实现LED灯亮灭
//				PAout(8) = 1;    
//				PDout(2) = 1;

				delay_ms(500);					     //延时500ms
				GPIO_ResetBits(GPIOA,GPIO_Pin_8);    //PA8,PD2低电平,L0,L1亮
				GPIO_ResetBits(GPIOD,GPIO_Pin_2);
//				PAout(8) = 0;
//				PDout(2) = 0;

				delay_ms(500);
		}
}
  led.h  
#ifndef __LED_H
#define __LED_H

void LED_Init(void);

#endif
  led.c  
#include<led.h>
#include<stm32f10x.h>

void LED_Init()
{
		GPIO_InitTypeDef GPIO_InitStructure;          //定义一个结构体
		
		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOD,ENABLE);	
		//PA,PD时钟使能,这里使用了或运算
		

		//定义PA8 GPIO口设置
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  //推挽输出
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;         //设置引脚
		GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //设置输出速度
		GPIO_Init(GPIOA,&GPIO_InitStructure);   		  //初始化GPIO口
		GPIO_SetBits(GPIOA,GPIO_Pin_8);                   //PA8输出高电平,L0灭
	
		
		//定义PD2 GPIO口设置
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  //推挽输出
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; 		  //设置引脚
		GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //设置输出速度
		GPIO_Init(GPIOD,&GPIO_InitStructure);	 		  //初始化GPIO口
		GPIO_SetBits(GPIOD,GPIO_Pin_2);					  //PD2输出高电平,L1灭
}