本文最后更新于170 天前,其中的信息可能已经过时,如有错误请发送邮件到
2871065713@qq.com
2025-10-15上课说项目管理复杂,要改项目结构。因此需要在项目根目录/usr新建led文件夹,创建led.c和led.h,并将原先main.c中的内容拆分开来,分别在led.h,led.c中实现各自的功能。下面给出能跑通的所有文件,以供参考。
//Led.c
#include "stm32f10x.h"
#include "led.h"
//↓函数名与main.c中led初始化相同,后面会标出。
void LedInit()
{
//ÅäÖÃ
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOE, &GPIO_InitStruct);
}
//Led.h
#ifndef DIO_LED_H
#define DIO_LED_H
#include "stm32f10x.h"
void LedInit(void);
#define Led1_Off() GPIO_WriteBit(GPIOB, GPIO_Pin_5, Bit_SET);
#define Led2_Off() GPIO_WriteBit(GPIOE, GPIO_Pin_5, Bit_SET);
#define Led1_On() GPIO_WriteBit(GPIOB, GPIO_Pin_5, Bit_RESET);
#define Led2_On() GPIO_WriteBit(GPIOE, GPIO_Pin_5, Bit_RESET);
#endif
//↑注意必须加空行不然会报warning。//main.c
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "led.h"
//#define S_GPIOB_BASE 0X40010C00
////#define S_CRL S_GPIO_BASE + 0x00
////#define S_ODR S_GPIO_BASE + 0x0C
//#define S_GPIOB ((GPIOA_PORTTypeDef*)S_GPIOB_BASE)
//typedef struct{
// uint32_t CRL;
// uint32_t IDR;
// uint32_t ODR;
// uint32_t BSRR;
// uint32_t BRR;
// uint32_t CKR;
//}GPIOA_PORTTypeDef;
//
void delay_ms(uint32_t ms){
uint32_t count = 10000;
while(ms --){
count = 10000;
while(count --);
}
}
//int main(void)
//{
// uint32_t temreg = 0;
// /* GPIOB Periph clock enable */
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// temreg = S_GPIOB->CRL;
// temreg &= 0xFF0FFFFF;
// temreg += 0x00200000;
// S_GPIOB->CRL = temreg;
//
// temreg = S_GPIOB->ODR;
// temreg &= 0x0EF;
// S_GPIOB->ODR = temreg;
// while(1);
//}
int main(void)
{
// ↓这个函数名对应led.c中的void LedInit();
LedInit();
while(1){
// ↓不要分开写,一起开关,分开写有bug,暂时没搞懂为啥
Led1_On();
Led2_Off();
delay_ms(500);
Led1_Off();
Led2_On();
delay_ms(500);
}
// ↓比如这样写只有红灯闪,绿灯不闪。
// while(1){
// Led1_On();
// delay_ms(500);
// Led1_Off();
// delay_ms(500);
// Led2_On();
// delay_ms(500);
// Led2_Off();
// delay_ms(500); }
// }
return 0;
}
