STM32F103ZE单片机不用定时器和中断,怎么设置一个变量在15和30之间来回变化
时间: 2024-02-24 10:58:40 浏览: 25
可以使用延时函数和GPIO控制来实现这个功能。具体步骤如下:
1. 在程序开始时,初始化GPIO口为输出模式,将变量初始值设置为15。
2. 进入主循环,先将GPIO口输出变量的值,然后使用延时函数延时一段时间。
3. 延时结束后,将变量的值加上15或减去15(根据当前变量的值来确定是加还是减),并判断变量是否在15和30之间,如果是,则不进行操作,如果不在这个范围内,则将变量的值设置为15或30。
4. 回到主循环,重复以上步骤。
示例代码如下:
```
#include "stm32f10x.h"
#define LED_GPIO_PORT GPIOB
#define LED_GPIO_PIN GPIO_Pin_0
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
}
void Delay(__IO uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
int main(void)
{
uint8_t value = 15;
uint8_t step = 15;
uint8_t direction = 1;
GPIO_Configuration();
while(1)
{
GPIO_WriteBit(LED_GPIO_PORT, LED_GPIO_PIN, (BitAction)value);
Delay(0xFFFFF);
if(direction == 1)
{
value += step;
if(value >= 30)
{
value = 30;
direction = -1;
}
}
else
{
value -= step;
if(value <= 15)
{
value = 15;
direction = 1;
}
}
}
}
```