STM32最简单的外设莫过于IO口的高低电平控制了, Proteus仿真STM32F103R6的跑马灯程序。
一、原理图
二、跑马灯C程序
// 粗略延时函数
static void delay(unsigned int n)
{
for(unsigned int i=0; i<n; i++)
{
for(unsigned int j=0; j<1024; j++)
{
for(unsigned int k=0; k<1024; k++)
{
__asm("nop");
}
}
}
}
int main(void)
{
// 使能GPIOB端口时钟
// RCC起始地址:0x40021000
// RCC_APB2ENR偏移地址:0x18
*(unsigned int *)(0x40021000 + 0x18) |= (1 << 3);
// 配置IO口为输出模式
// CNFy[1:0]: 00 - 通用推挽输出模式
// MODEy[1:0]:01 - 输出模式,最大速度10MHz
for(unsigned int i=0; i<8; i++)
{
// GPIOB起始地址:0x40010C00
// GPIOx_CRL偏移地址:0x00
*(unsigned int *)(0x40010C00 + 0x00) |= (1 << (4*i+0));
*(unsigned int *)(0x40010C00 + 0x00) &= ~(1 << (4*i+1));
*(unsigned int *)(0x40010C00 + 0x00) &= ~(1 << (4*i+2));
*(unsigned int *)(0x40010C00 + 0x00) &= ~(1 << (4*i+3));
}
// 设置IO口为高电平,关闭LED灯
// GPIOB起始地址:0x40010C00
// GPIOx_ODR地址偏移:0x0C
*(unsigned int *)(0x40010C00 + 0x0C) |= 0xFF;
while(1)
{
for(unsigned int i=0; i<8; i++)
{
// 设置IO口为低电平,打开LED灯
// GPIOB起始地址:0x40010C00
// GPIOx_ODR地址偏移:0x0C
*(unsigned int *)(0x40010C00 + 0x0C) &= ~(1 << i);
delay(1);
// 设置IO口为高电平,关闭LED灯
// GPIOB起始地址:0x40010C00
// GPIOx_ODR地址偏移:0x0C
*(unsigned int *)(0x40010C00 + 0x0C) |= (1 << i);
delay(1);
}
}
}