实现效果
1.红绿灯的切换
2.红灯、绿灯计时
所需材料:
1.LED发光二极管(红黄绿)
2.STM32
3.OLED
所需函数:
1.LED
2.延时
3.OLED函数
红灯:
定时10s
黄灯:
闪烁3s
绿灯:
定时10s
最后闪烁3s
main.c
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "LED.h"
uint16_t TimeR,,TimeG;
uint16_t i;
int main(void)
{
OLED_Init();//初始化
LED_Init();
while (1)
{
OLED_ShowString(1, 1, "Red:"); //红灯10s
for(TimeR = 10; TimeR <= 10; TimeR--)
{
LED1_ON();
OLED_ShowNum(1, 5, TimeR, 2);
Delay_s(1);
}
LED1_OFF();
OLED_Clear();
OLED_ShowString(1, 1, "Yel:"); //黄灯3s闪烁
for(i = 0 ; i <= 3; i++)
{
OLED_ShowNum(1, 5, 3-i, 2);
LED2_OFF();
Delay_ms(500);
LED2_ON();
Delay_ms(500);
}
LED2_OFF();
OLED_Clear();
OLED_ShowString(1, 1, "Gre:"); //绿灯7s常亮,3s闪烁
for(TimeG = 10; TimeG >= 4; TimeG--)
{
LED3_ON();
OLED_ShowNum(1, 5, TimeG, 2);
Delay_s(1);
}
for(i = 0 ; i <= 3; i++)
{
OLED_ShowNum(1, 5, 3-i ,2);
LED3_OFF();
Delay_ms(500);
LED3_ON();
Delay_ms(500);
}
LED3_OFF();
OLED_Clear();
}
}
LED.c
#include "stm32f10x.h" // Device header
void LED_Init(void) //初始化LED的GPIO口
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_3 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, GPIO_Pin_1 | GPIO_Pin_3| GPIO_Pin_5);
}
void LED1_ON(void) //红灯开
{
GPIO_ResetBits(GPIOA, GPIO_Pin_1);
}
void LED1_OFF(void) //红灯灭
{
GPIO_SetBits(GPIOA, GPIO_Pin_1);
}
void LED1_Turn(void) //红灯亮灭转换
{
if (GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_1) == 0)
{
GPIO_SetBits(GPIOA, GPIO_Pin_1);
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_1);
}
}
void LED2_ON(void) //黄灯亮
{
GPIO_ResetBits(GPIOA, GPIO_Pin_3);
}
void LED2_OFF(void) //黄灯灭
{
GPIO_SetBits(GPIOA, GPIO_Pin_3);
}
void LED2_Turn(void) //黄灯亮灭转换
{
{
if (GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_3) == 0)
{
GPIO_SetBits(GPIOA, GPIO_Pin_3);
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_3);
}
}
void LED3_ON(void) //绿灯亮
{
GPIO_ResetBits(GPIOA, GPIO_Pin_5);
}
void LED3_OFF(void) //绿灯灭
{
GPIO_SetBits(GPIOA, GPIO_Pin_5);
}
void LED3_Turn(void) //绿灯亮灭转换
{
if (GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_5) == 0)
{
GPIO_SetBits(GPIOA, GPIO_Pin_5);
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_5);
}
}