改成用寄存器操作实现四个灯的跑马灯
时间: 2024-02-16 22:02:54 浏览: 138
好的,下面是用寄存器操作实现四个灯的跑马灯的代码:
```c
#include "stm32f10x.h"
int main(void) {
// 使能 GPIOB 时钟
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
// 配置 PB0、PB1、PB2、PB12 为推挽输出模式,最大输出速率为 50MHz
GPIOB->CRL &= ~(GPIO_CRL_MODE0 | GPIO_CRL_MODE1 | GPIO_CRL_MODE2);
GPIOB->CRL |= (GPIO_CRL_MODE0_0 | GPIO_CRL_MODE1_0 | GPIO_CRL_MODE2_0);
GPIOB->CRH &= ~(GPIO_CRH_MODE12);
GPIOB->CRH |= GPIO_CRH_MODE12_0;
while (1) {
// 依次点亮 PB0、PB1、PB2、PB12
GPIOB->BSRR = GPIO_BSRR_BS0;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR0;
GPIOB->BSRR = GPIO_BSRR_BS1;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR1;
GPIOB->BSRR = GPIO_BSRR_BS2;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR2;
GPIOB->BSRR = GPIO_BSRR_BS12;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR12;
// 依次点亮 PB12、PB2、PB1、PB0
GPIOB->BSRR = GPIO_BSRR_BS12;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR12;
GPIOB->BSRR = GPIO_BSRR_BS2;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR2;
GPIOB->BSRR = GPIO_BSRR_BS1;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR1;
GPIOB->BSRR = GPIO_BSRR_BS0;
for (int i = 0; i < 1000000; i++);
GPIOB->BSRR = GPIO_BSRR_BR0;
}
}
```
这个代码可以让 PB0、PB1、PB2、PB12 这四个引脚的 LED 做跑马灯效果,每个灯亮 1 秒钟。
阅读全文