Bare metal C Ch07 GPIO - Hongjayeong-02/Basic_SoC_implementation GitHub Wiki
๋ชฉํ
GPIO code๋ฅผgpio.c/gpio.h๋ก ๋ชจ๋ํํ๊ณ , PB0 LED ์ถ๋ ฅ๊ณผ PC13 Button ์ ๋ ฅ์ ๊ตฌํํ๋ค.
๊ธฐ๋ฅ | Pin -- | -- LD1 Green LED | PB0 B1 User Button | PC13
GPIOB->BSRR = (1UL << LED_PIN);
์ read ์์ด ํ ๋ฒ์ write๋ก pin์ setํ๋ค.
bit 0~15 : Set
bit 16~31 : Reset
PB0:
GPIOB->BSRR = (1UL << 0);
GPIOB->BSRR = (1UL << 16);
main.c โ ๋ฌด์์ ํ ์ง
gpio.c โ GPIO๋ฅผ ์ด๋ป๊ฒ ์ ์ดํ ์ง
gpio.h โ ์ธ๋ถ์ ๊ณต๊ฐํ interface
Ch07_gpio/
โโโ Inc/
โ โโโ gpio.h
โโโ Src/
โโโ gpio.c
โโโ main.c
#ifndef GPIO_H
#define GPIO_H
#include <stdbool.h>
/* ---- LED (PB0, LD1 ๋
น์) ---- */
void led_init(void);
void led_on(void);
void led_off(void);
/* ---- Push Button (PC13, B1) ---- */
void button_init(void);
bool get_btn_state(void);
#endif /* GPIO_H */
#include "stm32f4xx.h"
#include "gpio.h"
#define LED_PIN 0U /* PB0 = LD1 (๋
น์) /
#define BTN_PIN 13U / PC13 = B1 */
void led_init(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
GPIOB->MODER &= ~(0x3UL << (LED_PIN * 2));
GPIOB->MODER |= (0x1UL << (LED_PIN * 2));
}
void led_on(void)
{
GPIOB->BSRR = (1UL << LED_PIN); /* Set */
}
void led_off(void)
{
GPIOB->BSRR = (1UL << (LED_PIN + 16)); /* Reset */
}
void button_init(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN;
GPIOC->MODER &= ~(0x3UL << (BTN_PIN * 2)); /* Input */
GPIOC->PUPDR &= ~(0x3UL << (BTN_PIN * 2)); /* No pull (๋ณด๋๊ฐ ์์ฒด ์ฒ๋ฆฌ) */
}
bool get_btn_state(void)
{
return (GPIOC->IDR & (1UL << BTN_PIN)) != 0U; /* active-HIGH */
}
#include "gpio.h"
int main(void)
{
bool btn_state;
led_init();
button_init();
while (1)
{
btn_state = get_btn_state();
if (btn_state)
{
led_on();
}
else
{
led_off();
}
}
}
GPIOB clock์ ์ผ๊ณ PB0์ output์ผ๋ก ์ค์ ํ๋ค.
GPIOB->BSRR = (1UL << LED_PIN);
GPIOB->BSRR = (1UL << (LED_PIN + 16));
GPIOC clock์ ์ผ๊ณ PC13์ input/no-pull๋ก ์ค์ ํ๋ค.
return (GPIOC->IDR & (1UL << BTN_PIN)) != 0U;
PC13 input ์ํ๋ฅผ boolean์ผ๋ก ๋ฐํํ๋ค.
B1
โ
โผ
PC13
โ
โผ
GPIOC->IDR
โ
โผ
get_btn_state()
โ
โโ true โ led_on()
โ
โโ false โ led_off()
โ
โผ
GPIOB->BSRR
โ
โผ
PB0
โ
โผ
LD1
Notion ๊ธฐ๋ก:
text = 800 bytes
data = 0 bytes
bss = 2560 bytes
GPIO input์
IDR๋ก ์ฝ๋๋ค.์ถ๋ ฅ set/reset์
BSRR๋ก ์ฒ๋ฆฌํ ์ ์๋ค.B1(PC13)์ project ๊ธฐ๋ก์ active-HIGH๋ค.
์ด Chapter๋ถํฐ peripheral driver๋ฅผ
.c/.h๋ก ๋ถ๋ฆฌํ๋ค.