跑马灯实验—库函数
1.使能IO时钟。调用函数RCC_AHB1PeriphClockCmd();不同的外设调用的时钟使能函数可能不一样
2.初始化IO口模式。调用函数GPIO_Init();
3.操作IO口,输出高低电平。GPIO_SetBits();GPIO_ResetBits();
跑马灯硬件电路
led.h
#ifndef __LED_H
#define __LED_H
void LED_Init(void);
#endif
led.c
#include "led.h"
#include "stm32f4xx.h"
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE); //使能GPIOF时钟
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10; //LED0和LED1对应的IO口
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_OUT; //普通输出模式
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP; //推挽输出
GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP; //上拉
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; //50MHZ
GPIO_Init(GPIOF,&GPIO_InitStructure);
GPIO_SetBits(GPIOF,GPIO_Pin_9|GPIO_Pin_10); //LED0=1,LED1=1
}
main.c
#include "stm32f4xx.h"
#include "led.h"
#include "delay.h"
int main(void)
{
delay_init(168); //初始化延时函数
LED_Init(); //初始化LED端口
while(1)
{
GPIO_ResetBits(GPIOF,GPIO_Pin_9); //LED0=0
GPIO_SetBits(GPIOF,GPIO_Pin_10); //LED1=1
delay_ms(500); //延时300ms
GPIO_SetBits(GPIOF,GPIO_Pin_9); //LED0=1
GPIO_ResetBits(GPIOF,GPIO_Pin_10); //LED1=0
delay_ms(500);
}
}
跑马灯实验—寄存器
1.使能IO口时钟。配置相关寄存器RCC->AHB1ENR
2.初始化IO口模式。配置四个配置寄存器GPIOx_MODER/GPIOx_OTYPER/GPIOx_OSPEEDR/GPIOx_PUPDR
3.操作IO口,输出高低电平。配置寄存器GPIOX_ODR或者BSRRL/BSRRH
led.c
#include "led.h"
#include "stm32f4xx.h"
void LED_Init(void)
{
RCC->AHB1ENR|=1<<5; //使能IO端口时钟
GPIOF->MODER &=~(3<<2*9); //通用输出模式
GPIOF->MODER |=1<<(2*9);
GPIOF->OSPEEDR &=~(3<<2*9); //50MHZ
GPIOF->OSPEEDR |=2<<(2*9);
GPIOF->PUPDR &=~(3<<2*9); //上拉
GPIOF->PUPDR |=1<<(2*9);
GPIOF->OTYPER &=~(1<<9); //推挽输出
GPIOF->OTYPER |=0<<9;
GPIOF->ODR|=1<<9; //GPIOF9=1
GPIOF->MODER &=~(3<<2*10);
GPIOF->MODER |=1<<(2*10);
GPIOF->OSPEEDR &=~(3<<2*10);
GPIOF->OSPEEDR |=2<<(2*10);
GPIOF->PUPDR &=~(3<<2*10);
GPIOF->PUPDR |=1<<(2*10);
GPIOF->OTYPER &=~(1<<10);
GPIOF->OTYPER |=0<<10;
GPIOF->ODR|=1<<10;
}
main.c
#include "stm32f4xx.h"
#include "led.h"
#include "delay.h"
int main(void)
{
delay_init(168);
LED_Init();
while(1)
{
GPIO->ODR &=~(1<<9);
GPIO->ODR &=~(1<<10);
delay_ms(500);
GPIO->ODR |=1<<9;
GPIO->ODR |=1<<10;
delay(500);
}
}
跑马灯实验---位操作
1.使能IO口时钟。调用函数RCC_AHB1PeriphClockCmd();
2.初始化IO口模式。调用函数GPIO_Init();
3.操作IO口,输出高低电平。使用位带操作。
main.c
#include "stm32f4xx.h"
#include "led.h"
#include "delay.h"
int main(void)
{
delay_init(168);
LED_Init();
while(1)
{
PFout(9)=1;
PFout(10)=1;
delay_ms(500);
PFout(9)=0;
PFout(10)=0;
delay_ms(500);
}
}