1、使用固件库进行编程,点亮led灯。
2、使用带宏参数定义,简化主程序。
#ifndef __LED_H__
#define __LED_H__
#include "stm32f10x.h"
#define LED_R_GPIO_PIN GPIO_Pin_5//红灯
#define LED_G_GPIO_PIN GPIO_Pin_0//绿灯
#define LED_B_GPIO_PIN GPIO_Pin_1//蓝灯
#define LED_RGB_GPIO_PORT GPIOB
#define LED_RGB_GPIO_CLK RCC_APB2Periph_GPIOB
#define LED_ON 1
#define LED_OFF 0
#define LED_R(x) if(x)GPIO_ResetBits(LED_RGB_GPIO_PORT, LED_R_GPIO_PIN );\
else GPIO_SetBits(LED_RGB_GPIO_PORT , LED_R_GPIO_PIN );
#define LED_G(x) if(x)GPIO_ResetBits(LED_RGB_GPIO_PORT, LED_G_GPIO_PIN );\
else GPIO_SetBits(LED_RGB_GPIO_PORT , LED_G_GPIO_PIN );
#define LED_B(x) if(x)GPIO_ResetBits(LED_RGB_GPIO_PORT, LED_B_GPIO_PIN );\
else GPIO_SetBits(LED_RGB_GPIO_PORT , LED_B_GPIO_PIN );
void LED_config(uint8_t LED_R, uint8_t LED_G, uint8_t LED_B);
#endif /*__LED_H__*/
#include "led.h"
void LED_config(uint8_t LED_R,uint8_t LED_G,uint8_t LED_B)
{
GPIO_InitTypeDef GPIO_INIT_struct;//声明一个结构体类型的指针变量
RCC_APB2PeriphClockCmd(LED_RGB_GPIO_CLK, ENABLE);//ENABLE表示1 ,操作GPIO外设的时候必须先开启外设时钟,要不然操作无法成功
if (LED_R+LED_G+LED_B)
{
if (LED_R)
{
GPIO_INIT_struct.GPIO_Pin = LED_R_GPIO_PIN;//配置哪个引脚
GPIO_INIT_struct.GPIO_Mode = GPIO_Mode_Out_PP;//配置推挽输出
GPIO_INIT_struct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_RGB_GPIO_PORT, &GPIO_INIT_struct);
GPIO_SetBits(LED_RGB_GPIO_PORT, LED_R_GPIO_PIN);//关闭灯,默认初始化后io端口输出低电平
}
if (LED_G)
{
GPIO_INIT_struct.GPIO_Pin = LED_G_GPIO_PIN;//配置哪个引脚
GPIO_INIT_struct.GPIO_Mode = GPIO_Mode_Out_PP;//配置推挽输出
GPIO_INIT_struct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_RGB_GPIO_PORT, &GPIO_INIT_struct);
GPIO_SetBits(LED_RGB_GPIO_PORT, LED_G_GPIO_PIN);//关闭灯,默认初始化后io端口输出低电平
}
if (LED_B)
{
GPIO_INIT_struct.GPIO_Pin = LED_B_GPIO_PIN;//配置哪个引脚
GPIO_INIT_struct.GPIO_Mode = GPIO_Mode_Out_PP;//配置推挽输出
GPIO_INIT_struct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_RGB_GPIO_PORT, &GPIO_INIT_struct);
GPIO_SetBits(LED_RGB_GPIO_PORT, LED_B_GPIO_PIN);//关闭灯,默认初始化后io端口输出低电平
}
}
else
{
return;
}
}
#include "stm32f10x.h"
#include "led.h"
void delay(uint32_t x);
int main(void)
{
LED_config( 1,1,1);
while(1)
{
LED_R(LED_ON);
delay(10000);
LED_R(LED_OFF);
delay(10000);
LED_G(LED_ON);
delay(10000);
LED_G(LED_OFF);
delay(10000);
LED_B(LED_ON);
delay(10000);
LED_B(LED_OFF);
delay(10000);
}
}
void delay(uint32_t x)
{
uint32_t y;
for(;x>0;x--)
for(y=1000;y>0;y--);
}