STM32入门:GPIO配置与基本操作(条件编译及移位运算)

简介

本文介绍如何使用STM32F103C8T6的GPIO实现呼吸灯效果,重点讲解条件编译和移位运算的应用。

硬件配置

  • 芯片型号:STM32F103C8T6
  • 时钟频率:72MHz
  • 使用引脚:PC13

GPIO初始化

void gpio_init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
    
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
    GPIO_SetBits(GPIOC, GPIO_Pin_13);  // 默认熄灭
}

条件编译应用

通过定义USE_PWM宏来选择LED控制方式:

#ifdef USE_PWM
    #define LED_ON() GPIO_SetBits(GPIOC, GPIO_Pin_13)
    #define LED_OFF() GPIO_ResetBits(GPIOC, GPIO_Pin_13)
#else
    #define LED_ON() GPIO_ResetBits(GPIOC, GPIO_Pin_13)
    #define LED_OFF() GPIO_SetBits(GPIOC, GPIO_Pin_13)
#endif

移位运算实现PWM

使用移位运算计算占空比,实现呼吸灯效果:

void pwm_breath(void)
{
    static unsigned int step = 0;
    static unsigned int direction = 1;  // 1:变亮, 0:变暗
    unsigned int on_time, off_time;
    
    // 根据step计算占空比和相应的亮灭时间
    if(direction) {
        on_time = step * (PWM_PERIOD / PWM_STEPS);
        off_time = PWM_PERIOD - on_time;
    } else {
        off_time = step * (PWM_PERIOD / PWM_STEPS);
        on_time = PWM_PERIOD - off_time;
    }
    
    // 控制LED
    LED_ON();
    delay_ms(on_time);
    LED_OFF();
    delay_ms(off_time);
    
    // 更新step
    if(direction) {
        step++;
        if(step >= PWM_STEPS) {
            step = PWM_STEPS - 1;
            direction = 0;
        }
    } else {
        step--;
        if(step == 0) {
            direction = 1;
        }
    }
}

主函数

int main(void)
{
    gpio_init();
    delay_init();
    
    while (1)
    {
        pwm_breath();
    }
}

总结

通过条件编译和移位运算在嵌入式开发中的应用。这些技术可以很大提高代码的执行效率。

更多推荐