一、C程序中可使用不同类型的变量来进行延时设计。经实验测试,使用unsigned char类型具有比unsigned int更优化的代码,在使用时应该使用unsigned char作为延时变量。
方法一:使用for循环来延时
void delay(unsigned int time)
{
unsigned int i = 0;
unsigned int j = 0;
for(i = 0; i < time; i++)
{
for(j = 0; j < 1000; j++);
}
}
二、流水灯的简单实现
1、首先,封装一个GPIO引脚初始化函数
void init(uint16_t pin)
{
GPIO_InitTypeDef GPIO_InitStruct; //参数配置结构体
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE); //打开端口E的时钟
GPIO_InitStruct.GPIO_Pin = pin;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOE, &GPIO_InitStruct); //参数结构体应用于硬件初始化
}
2、点亮流水灯的逻辑代码
方法一:使用GPIO_ResetBits和GPIO_SetBits函数进行实现
while(1)
{
GPIO_ResetBits(GPIOE, GPIO_Pin_12); //打开LED
delay(1000);
GPIO_SetBits(GPIOE, GPIO_Pin_12); //关闭LED
delay(1000);
GPIO_ResetBits(GPIOE, GPIO_Pin_13); //´ò¿ªLED
delay(1000);
GPIO_SetBits(GPIOE, GPIO_Pin_13); //¹Ø±ÕLED
delay(1000);
GPIO_ResetBits(GPIOE, GPIO_Pin_14); //´ò¿ªLED
delay(1000);
GPIO_SetBits(GPIOE, GPIO_Pin_14); //¹Ø±ÕLED
delay(1000);
}
方法二:使用库内函数读取引脚的电平值取非,并进行状态的写入
while(1)
{
GPIO_WriteBit(GPIOE, GPIO_Pin_12, !GPIO_ReadOutputDataBit(GPIOE, GPIO_Pin_12));
delay(1000);
}
uint8_t GPIO_ReadOutputDataBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void GPIO_WriteBit(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, BitAction BitVal);
方法三:使用库函数GPIO_Write一次操作多个引脚
规律:
LED1(pin12) LED2 LED3
ON OFF OFF
OFF ON OFF
OFF OFF ON
注:C语言中的移位都是对1移位
32位中, 1 表示为 0000 0000 0000 0001
1 << 12 结果:0001 0000 0000 0000
~(1 << 12) 结果:1110 1111 1111 1111(此时就可以把LED开,其余关闭)
for(i = 0; i < 3; i++)
{
GPIO_Write(GPIOE, ~(1 << (12 + i)));
delay(1000);
}
方法四:方法三中,仅是把需要改变的位置进行了移位得到,但是这同时也改变了其他引脚位的值,会出现操作紊乱,因此,我们需要做的是,把需改动的位置的数字改变,同时确保其他引脚的值不改变
比如:开始时引脚的信息情况为:
1、 xxxx xxxx xxxx xxxx
2、把需要改动的位置置零,如14、13、12号引脚的值为 (110,101,011),为了得到此值,需要将原先的值与0x8FFF按位&操作
3、把需改变的位通过移位得到,~(1 << (12 + i)),将其与0x7000按位&,确保所需位保持1,其余位置零
4、将第2、3步得到的结果按位或
至此,就将需要的位保存所需值,其余位保持原始状态
for(i = 0; i < 3; i++)
{
GPIO_Write(GPIOE, (GPIO_ReadOutputData(GPIOE) & 0x8FFF) | (~(1 << (12 + i)) & 0x7000));
delay(1000);
}