学习STM32的入门课程,从点亮和熄灭LED小灯做起。
本次实验使用STM32F103RC的芯片,其中LED1接到STM32芯片的PA8引脚,LED2接到STM32芯片的PB15引脚,如下图:
LED小灯的电路暂不上传,其中PA8和PB15为低电平的时候,LED1和LED2灯点亮;高电平的时候,LED1和LED2灯熄灭。
有了以上的理论基础,下面在Keil5中新建工程,关于工程的创建和里面细节的配置和库文件的引用,本文不做描述。
代码如下,有几种方式,可以分别尝试:
#include "stm32f10x.h"
void GPIO_Init_(void)
{
GPIO_InitTypeDef GPIO_InitStructure_A, GPIO_InitStructure_B;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure_B.GPIO_Pin = GPIO_Pin_15;
GPIO_InitStructure_B.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure_B.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure_B);
GPIO_InitStructure_A.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure_A.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure_A.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure_A);
}
int main()
{
uint32_t tmp = 0;
SystemInit();
GPIO_Init_();
while (1)
{
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_ResetBits(GPIOB, GPIO_Pin_15);
for (tmp = 0; tmp < 3000000; tmp++);
GPIO_ResetBits(GPIOA, GPIO_Pin_8);
GPIO_SetBits(GPIOB, GPIO_Pin_15);
for (tmp = 0; tmp < 3000000; tmp++);
}
}
int main03()
{
uint32_t tmp = 0;
SystemInit();
GPIO_Init_();
while (1)
{
GPIO_WriteBit(GPIOA, GPIO_Pin_8, (BitAction)0x01);
GPIO_WriteBit(GPIOB, GPIO_Pin_15, (BitAction)0x00);
for (tmp = 0; tmp < 3000000; tmp++);
GPIO_WriteBit(GPIOA, GPIO_Pin_8, (BitAction)0x00);
GPIO_WriteBit(GPIOB, GPIO_Pin_15, (BitAction)0x01);
for (tmp = 0; tmp < 3000000; tmp++);
}
}
int main02()
{
uint32_t tmp = 0;
SystemInit();
GPIO_Init_();
while (1)
{
GPIOA->BRR = 0x0100;
GPIOB->BSRR = 0x8000;
for (tmp = 0; tmp < 3000000; tmp++);
GPIOA->BSRR = 0x0100;
GPIOB->BRR = 0x8000;
for (tmp = 0; tmp < 3000000; tmp++);
}
}
int main01()
{
uint32_t tmp = 0;
SystemInit();
GPIO_Init_();
while (1)
{
GPIOA->ODR = 0xffff;
GPIOB->ODR = 0x7fff;
for (tmp = 0; tmp < 3000000; tmp++);
GPIOA->ODR = 0xfeff;
GPIOB->ODR = 0xffff;
for (tmp = 0; tmp < 3000000; tmp++);
/*
GPIO_Write(GPIOA, 0xffff);
GPIO_Write(GPIOB, 0x7fff);
for (tmp = 0; tmp < 3000000; tmp++);
GPIO_Write(GPIOA, 0xfeff);
GPIO_Write(GPIOB, 0xffff);
for (tmp = 0; tmp < 3000000; tmp++);
*/
}
}
执行以上的代码,可以看到板子上的LED小灯交叉亮灭。