STM32 LED Control Using GPIOX_IDR and ODR: Blue Button Toggle
Here is a sample code using GPIOX_IDR and ODR to control the inbuilt LED on an STM32 microcontroller:
#include "stm32f4xx.h"
void delay(void)
{
for(uint32_t i=0; i<500000; i++);
}
int main(void)
{
// Enable the GPIOA and GPIOD peripheral clock
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN;
// Set GPIOA pin 0 (blue button) as input
GPIOA->MODER &= ~(GPIO_MODER_MODER0);
// Set GPIOD pin 12 (LED) as output
GPIOD->MODER &= ~(GPIO_MODER_MODER12);
GPIOD->MODER |= GPIO_MODER_MODER12_0;
while(1)
{
if(GPIOA->IDR & GPIO_IDR_IDR_0) // Check if blue button is pressed
{
GPIOD->ODR |= GPIO_ODR_ODR_12; // Turn on the LED
}
else
{
GPIOD->ODR &= ~GPIO_ODR_ODR_12; // Turn off the LED
}
delay(); // Delay for a short period of time
}
}
In this code, we first enable the clock for GPIOA and GPIOD peripherals. Then, we set GPIOA pin 0 as input and GPIOD pin 12 as output. Inside the infinite while loop, we check the status of GPIOA pin 0 using GPIOX_IDR register. If the pin is high (button is pressed), we set GPIOD pin 12 high to turn on the LED. Otherwise, we set GPIOD pin 12 low to turn off the LED. We also include a delay function to add a small delay between each loop iteration.
原文地址: http://www.cveoy.top/t/topic/o9i 著作权归作者所有。请勿转载和采集!