0%

3-2LED闪烁&LED流水灯&蜂鸣器

LED闪烁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "stm32f10x.h"                  // Device header
#include "delay.h"
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
while(1)
{
//GPIO_ResetBits(GPIOA,GPIO_Pin_0);
//Delay_ms(500);
//GPIO_SetBits(GPIOA,GPIO_Pin_0);
//Delay_ms(500);
//GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_SET);
//Delay_ms(500);
//GPIO_WriteBit(GPIOA,GPIO_Pin_0,Bit_RESET);
//Delay_ms(500);
GPIO_WriteBit(GPIOA,GPIO_Pin_0,(BitAction)0);
Delay_ms(500);
GPIO_WriteBit(GPIOA,GPIO_Pin_0,(BitAction)1);
Delay_ms(500);
}
}

(BitAction)0为强制类型转换,把1和0类型转换为BitAction的枚举类型。
LED无论是长脚插在PA0口(高电平),还是短脚插在PA0口(低电平),都会闪烁,说明:在推挽模式下,高低电平都有驱动能力。

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
改为GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
只能短脚插在PA0,灯会闪烁。长脚插PA0,灯灭。
说明开漏模式的高电平是没有驱动能力的,相当于高阻态。

LED流水灯

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "stm32f10x.h"                  // Device header
#include "delay.h"
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
while(1)
{
GPIO_Write(GPIOA,~0x0001);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0002);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0004);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0008);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0010);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0020);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0040);//0000 0000 0000 0001
Delay_ms(500);
GPIO_Write(GPIOA,~0x0080);//0000 0000 0000 0001
Delay_ms(500);
}
}

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;可以通过按位或的方式使能多个GPIO口。

蜂鸣器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "stm32f10x.h"                  // Device header
#include "delay.h"
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
while(1)
{
GPIO_SetBits(GPIOB,GPIO_Pin_12);
Delay_ms(100);
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
Delay_ms(100);
GPIO_SetBits(GPIOB,GPIO_Pin_12);
Delay_ms(700);
GPIO_ResetBits(GPIOB,GPIO_Pin_12);
Delay_ms(100);
}
}