前言
本篇文章属于stm32单片机(以下简称单片机)的学习笔记,来源于B站教学视频。下面是这位up主的视频链接。本文为个人学习笔记,只能做参考,细节方面建议观看视频,肯定受益匪浅。
STM32入门教程-2023版 细致讲解 中文字幕_哔哩哔哩_bilibili
一、GPIO简介

二、GPIO基本结构

三、GPIO位结构

施密特触发器的原理

红线是输入电平,蓝线是整流后的电平,绿线是上限和下限
当波形越过上限或下限时,电平才会发生改变,假如只在下限周围上下浮动是电平是不会发生变化的
位设置/清除寄存器的使用原理 :如果要在某位上置1,而其它位保持不变,就在位设置寄存器中,给这对应位置1,其它位置0,这样这个位就会被置为1,其它位不变,省去了C语言&=和|=复杂繁琐的操作;置0则在位清除寄存器置1即可,其它置0的保持不变。

**推挽:**两个MOS管均起作用,输出给1时,P-MOS导通,N-MOS截止,输出高电平;输出给0时,P-MOS截止,N-MOS导通,输出低电平,此时高低电平均有驱动能力。
**开漏:**P-MOS管不起作用,只有N-MOS管有用, 输出给1时,N-MOS截止,输出高电平;输出给0时,N-MOS导通,输出低电平,此时高电平没有驱动能力,只有低电平有驱动能力,主要应用于总线挂载多个设备是防止多个设备的互相干扰或者可以在IO口配置一个上拉电阻,输出0时,N-MOS导通,输出低电平,而输出1时,N-MOS截止,IO口的上拉电阻可以将IO口拉至5V来驱动电路。
**关闭:**当引脚配置为输入模式时,两个MOS均关闭,不起输出作用。
四、GPIO模式

只输入,输出开关是断开的,而输出的时候,输入也是可以进来的,除了模拟输入会关闭数字输入的功能,其它七个模式输入都是有效的。
五、硬件电路
上面两个图是低电平导通,高电平截止
下面两个图是高电平导通,低电平截止
六、实例一(LED闪烁)
1. 接线图

2. 代码
#include "stm32f10x.h" // Device header
#include "Delay.h"
int main(void)
{
//启动时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//初始化GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
while (1)
{
//写入数据,输出
GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_RESET);
Delay_ms(500);
GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_SET);
Delay_ms(500);
}
}
七、实例二(LED流水灯)
1.接线图

2.代码
#include "stm32f10x.h" // Device header
#include "Delay.h"
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_All;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
while (1)
{
GPIO_Write(GPIOA, ~0x0001); //0000 0000 0000 0001
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0002); //0000 0000 0000 0010
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0004); //0000 0000 0000 0100
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0008); //0000 0000 0000 1000
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0010); //0000 0000 0001 0000
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0020); //0000 0000 0010 0000
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0040); //0000 0000 0100 0000
Delay_ms(50);
GPIO_Write(GPIOA, ~0x0080); //0000 0000 1000 0000
Delay_ms(50);
}
}
八、实例三(蜂鸣器)
1.接线图

2.代码
#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_WriteBit(GPIOB, GPIO_Pin_12, Bit_RESET);
Delay_ms(100);
GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_SET);
Delay_ms(100);
GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_RESET);
Delay_ms(100);
GPIO_WriteBit(GPIOB, GPIO_Pin_12, Bit_SET);
Delay_ms(700);
}
}
其为有源蜂鸣器,给低电平就会响