stm32f103c8t6按键流水灯代码
时间: 2023-08-23 07:06:41 浏览: 67
stm32f103c8t6代码
5星 · 资源好评率100%
以下是基于STM32CubeIDE的stm32f103c8t6按键流水灯代码示例:
```c
#include "main.h"
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
uint8_t led_num = 0;
uint8_t button_state = 0;
while (1)
{
button_state = HAL_GPIO_ReadPin(BUTTON_GPIO_Port, BUTTON_Pin);
if(button_state == GPIO_PIN_RESET)
{
led_num++;
if(led_num > 7)
{
led_num = 0;
}
}
HAL_GPIO_WritePin(LED_0_GPIO_Port, LED_0_Pin, (led_num == 0) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_1_GPIO_Port, LED_1_Pin, (led_num == 1) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_2_GPIO_Port, LED_2_Pin, (led_num == 2) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_3_GPIO_Port, LED_3_Pin, (led_num == 3) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_4_GPIO_Port, LED_4_Pin, (led_num == 4) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_5_GPIO_Port, LED_5_Pin, (led_num == 5) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_6_GPIO_Port, LED_6_Pin, (led_num == 6) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_GPIO_WritePin(LED_7_GPIO_Port, LED_7_Pin, (led_num == 7) ? GPIO_PIN_SET : GPIO_PIN_RESET);
HAL_Delay(100);
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
GPIO_InitStruct.Pin = BUTTON_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(BUTTON_GPIO_Port, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LED_0_Pin|LED_1_Pin|LED_2_Pin|LED_3_Pin
|LED_4_Pin|LED_5_Pin|LED_6_Pin|LED_7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}
```
本示例代码假定:按键连接到PC13,LEDs连接到PC0-PC7。在按下按键时,LEDs将顺序闪烁,直到所有LED都开启,然后重新开始顺序闪烁。
您需要将此代码复制到您的STM32CubeIDE项目中,并根据实际硬件连接和需求进行修改。
阅读全文