文章目录
- 一、介绍GPIO
- 简介GPIO
- GPIO基本结构
- GPIO位结构
- GPIO模式
- 二、外设介绍
- LED、蜂鸣器简介
- 硬件电路
- 面包板介绍
- 三、实现LED闪烁
- 连接LED线路
- 具体程序
- 引入Delay
- 具体代码如下:
- 四、实现流水灯
- 组装线路
- 根据GPIO_Init中结构体成员GPIO_Pin的定义,可以使用或运算来选择多个IO口
- 具体代码
- 五、蜂鸣器
- 连接线路
- 代码实现
一、介绍GPIO
简介GPIO
GPIO基本结构
GPIO位结构
肖特基触发器:翻译错误,是施密特触发器,避免电压失真导致电压不稳定,实现模拟图如下:
GPIO模式
浮空/上拉/下拉
模拟输入:直接输出模拟信号
开漏/推挽:通过两个mos管,由输出寄存器来控制引脚电平,开漏只有N-mos有效,只能低电平驱动;推挽,则高低电平都可以。
通用开漏/推挽:对比普通开漏/推挽把输出控制交给了外设控制
位设置/清除寄存器
二、外设介绍
LED、蜂鸣器简介
硬件电路
负载一般接在电源极,即开关开断处接发射极,不然可能因为开关开启电压导致三极管无法开启
面包板介绍
上面电源是一横排互通,中间为一纵列互通,以下为基础LED连接示例
三、实现LED闪烁
连接LED线路
具体程序
引入Delay
将Delay相关函数存放于项目同级目录System下,并加入System组中,和之前配置启动文件一样,然后记得加入头文件目录
具体代码如下:
#include "stm32f10x.h" // Device header
#include "Delay.h"
int main(){
// Enables or disables the High Speed APB (APB2) peripheral clock
// 打开时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//Initializes the GPIOx peripheral according to the specified *parameters in the GPIO_InitStruct
// 使用结构体设置相关通用IO口
GPIO_InitTypeDef GPIO_Structure;
GPIO_Structure.GPIO_Pin = GPIO_Pin_0;
GPIO_Structure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Structure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA,&GPIO_Structure);
// Clears the selected data port bits
// 给低电平
// GPIO_ResetBits(GPIOA,GPIO_Pin_0);
// Sets the selected data port bits
// 给高电平
// GPIO_SetBits(GPIOA,GPIO_Pin_0);
// Sets or clears the selected data port bit
// 设置这个选择的位为高电平(Bit_SET)或低电平(Bit_RESET)
// GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_RESET);
while(1){
GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_SET);
Delay_ms(500);
GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_RESET);
Delay_ms(500);
}
// return 0; // 可以不返回,返回反而有警告
}
四、实现流水灯
组装线路
根据GPIO_Init中结构体成员GPIO_Pin的定义,可以使用或运算来选择多个IO口
具体代码
#include "stm32f10x.h" // Device header
#include "Delay.h"
int main(){
unsigned char i;
// Enables or disables the High Speed APB (APB2) peripheral clock
// 打开时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
//Initializes the GPIOx peripheral according to the specified *parameters in the GPIO_InitStruct
// 使用结构体设置相关通用IO口
GPIO_InitTypeDef GPIO_Structure;
GPIO_Structure.GPIO_Pin = GPIO_Pin_All;
GPIO_Structure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Structure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA,&GPIO_Structure);
// Writes data to the specified GPIO data port.
// 配置所选组
// GPIO_Write(GPIOA,0x00000001);
while(1){
for(i=0;i<8;i++){
GPIO_Write(GPIOA,~(0x00000001<<i));
Delay_ms(500);
}
}
// return 0;
}
五、蜂鸣器
连接线路
代码实现
#include "stm32f10x.h" // Device header
#include "Delay.h"
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
while (1)
{
GPIO_ResetBits(GPIOB, GPIO_Pin_12);
Delay_ms(100);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
Delay_ms(100);
GPIO_ResetBits(GPIOB, GPIO_Pin_12);
Delay_ms(100);
GPIO_SetBits(GPIOB, GPIO_Pin_12);
Delay_ms(700);
}
}