一闪一闪亮晶晶—led灯闪烁
Goals
最小系统板上有两个led,一个是电源指示灯,另一个是连在GPIO上的。
让连在GPIO上的led闪烁,频率随意。
what do you want?
1、最小系统电路图
led与哪一个GPIO相连
2、延时函数
3、GPIO配置函数
Material
hardware material
1、电路图
驱动 PC13 端口即可
software materail
1、延时函数
使用正点原子提供的SYSTEM文件夹里面的delay文件
#include "delay.h"
void delay_init(void);
void delay_ms(u16 nms);
void delay_us(u32 nus);
2、GPIO配置函数
使用正点原子提供的SYSTEM文件夹里面的sys文件,
其对stm32f10x.h做了进一步封装,增加了IO口的位带操作
#include "sys.h"
// enable the clock of the port
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
// setting the mode of the port
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_pp;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure)
// setting the level of the port
GPIO_SetBits(GPIOC, GPIO_Pin_13); // setting hight
GPIO_ResetBits(GPIOC, GPIO_Pin_13); // setting low
Procedure
1、确定业务目标后,提取其要点收集对应原材料
2、创建工程
复制模板工程更改工程名相关属性
新增HATDWARE文件夹,进入后新建LED子文件夹,进入后新建led.c, led.h
目录结构为:
- USER
- main.c
- stm32f10x_it.c
- system_stm32f10x.c
- 还有对应的.h,还有Objects, Listings, DebugConfig
- SYSTEM
- delay
- delay.c
- delay.h
- sys
- sys.c
- sys.h
- usart
- usart.c
- usart.h
- delay
- HARDWARE
- LED
- led.c
- led.h
- LED
- STM32F10x_FWLib
- CORE
3、编写led.c 和 led.h
led.h
#ifndef __LED_H
#define __LED_H
#include "sys.h"
// Define the port of LED
#define LED PCout(13)
void LED_Init(void); // Initailize the port of LED
void LED_Light(void); // LED on
void LED_Dark(void); // LED off
#endif
led.c
#include "led.h"
// Initailize the port of LED
void LED_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
// Enable the clock of the port B
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
// Let the mode of PC13 is push-pull out
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
// Let the level of PC13 is heght
GPIO_SetBits(GPIOC, GPIO_Pin_13);
}
// LED on
void LED_Dark(void) {
// Let the level of PC13 is height
GPIO_SetBits(GPIOC, GPIO_Pin_13);
}
// LED off
void LED_Light(void) {
// Let the level of PC13 is low
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
}
4、编写main.c
#include "delay.h"
#include "usart.h"
#include "led.h"
int main(void) {
delay_init();
LED_Init();
while(1) {
delay_ms(100);
LED_Light();
delay_ms(100);
LED_Dark();
}
}
5、编译下载
Summary & Supplement
1、三种改变单个IO口状态的方法
(1)位带操作
#define LED PCout(13)
LED = 1; // the level of the port is heght, but the led is dark
LED = 0; // the level of the port is low, but the led is light
(2)库函数操作
GPIO_SetBits(GPIOC, GPIO_Pin_13); // the level of the port is heght, but the led is dark
GPIO_ResetBits(GPIOC, GPIO_Pin_13); // the level of the port is low, but the led is light
(3)寄存器操作
GPIOC->BRR = GPIO_Pin_13; // the level of the port is heght, but the led is dark
GPIOC->BSRR = GPIO_Pin_13; // the level of the port is low, but the led is light