STM32实现LED闪烁
一、熟悉STM32
STM32是ST公司基于ARM Cortex-M内核开发的32位微控制器,在嵌入式领域应用极为广泛。
STM32的主流为STM32F1系列,其内核为ARM Cortex-M3,主频为72MHz.
系统结构:
片上外设资源(常用):
二、GPIO的八种工作模式
GPIO(General Purpose Input Output):通用输入输出口。
引脚电平:0V~3.3V。
输出模式下可控制端口输出高低电平。
输入模式下可读取端口的高低电平或电压。
IO口的基本结构;
GPIO的八种工作模式:
三、LED的代码实现
LED:发光二极管,正向通电点亮,反向通电不亮.
实物图连接:
源码:
main.c
#include "stm32f10x.h"
#include "Delay.h"
int main(void)
{
//使能GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//定义GPIOA结构体
GPIO_InitTypeDef GPIO_InitStruct;
//结构体成员
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_All;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
//调用 GPIO_Init 函数初始化 GPIOA
GPIO_Init(GPIOA,&GPIO_InitStruct);
while(1)
{
GPIO_Write(GPIOA, ~0x0001); //0000 0000 0000 0001
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0002); //0000 0000 0000 0010
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0004); //0000 0000 0000 0100
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0008); //0000 0000 0000 1000
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0010); //0000 0000 0001 0000
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0020); //0000 0000 0010 0000
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0040); //0000 0000 0100 0000
Delay_ms(100);
GPIO_Write(GPIOA, ~0x0080); //0000 0000 1000 0000
Delay_ms(100);
}
}
Delay.c
#include "stm32f10x.h"
/**
* @brief 微秒级延时
* @param xus 延时时长,范围:0~233015
* @retval 无
*/
void Delay_us(uint32_t xus)
{
SysTick->LOAD = 72 * xus; //设置定时器重装值
SysTick->VAL = 0x00; //清空当前计数值
SysTick->CTRL = 0x00000005; //设置时钟源为HCLK,启动定时器
while(!(SysTick->CTRL & 0x00010000)); //等待计数到0
SysTick->CTRL = 0x00000004; //关闭定时器
}
/**
* @brief 毫秒级延时
* @param xms 延时时长,范围:0~4294967295
* @retval 无
*/
void Delay_ms(uint32_t xms)
{
while(xms--)
{
Delay_us(1000);
}
}
/**
* @brief 秒级延时
* @param xs 延时时长,范围:0~4294967295
* @retval 无
*/
void Delay_s(uint32_t xs)
{
while(xs--)
{
Delay_ms(1000);
}
}