如何用stm32编一个8流水灯两两一组控制程序
时间: 2024-04-29 16:19:50 浏览: 48
您好!下面是基于STM32的8个流水灯两两一组控制程序的示例代码。在代码中,使用GPIO控制器和定时器控制器来控制LED的闪烁。
```c
#include "stm32f10x.h"
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
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_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
uint16_t PrescalerValue = 0;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
PrescalerValue = (uint16_t) (SystemCoreClock / 1000000) - 1;
TIM_TimeBaseStructure.TIM_Period = 99;
TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_Cmd(TIM2, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
}
int main(void)
{
uint16_t LED[8] = {GPIO_Pin_0, GPIO_Pin_1, GPIO_Pin_2, GPIO_Pin_3, GPIO_Pin_4, GPIO_Pin_5, GPIO_Pin_6, GPIO_Pin_7};
uint16_t i, j, k, m;
GPIO_Configuration();
TIM_Configuration();
while (1)
{
for (j = 0; j < 2; j++)
{
for (i = 0; i < 8; i += 2)
{
m = 1 << i;
k = m | (m << 1);
GPIO_SetBits(GPIOA, LED[k]);
GPIO_ResetBits(GPIOA, LED[k ^ 0xff]);
TIM_SetCompare1(TIM2, 50);
Delay(200);
TIM_SetCompare1(TIM2, 0);
}
}
}
}
void Delay(__IO uint32_t nCount)
{
for (; nCount != 0; nCount--);
}
```
在这个例子中,我们使用GPIO控制器和定时器控制器来控制8个LED灯的闪烁。使用定时器的PWM功能来控制LED的亮度。在程序的主循环中,使用两个嵌套的循环来控制LED的闪烁。首先循环两次,然后在每次循环中,循环两次来控制两个LED灯的闪烁。
希望这个例子能够对您有所帮助。如果您有任何问题,请随时问我。
阅读全文