CPU 에서 기본적으로 사용이 되는 GPIO를 사용해보도록 한다.
기본프로젝트를 다운로드 받는다. 어디? 여기에!
사용될 GPIO 핀
먼저 사용될 핀을 찾아보자.
LED 회로



Switch 회로


정리 하자면 사용되는 GPIO 핀은 다음과 같다.
| 기능 | 사용목적 | Netname | 포트명 |
| GPIO | Output | SYS_USER_LED1 | PG12 |
| GPIO | Output | SYS_USER_LED2 | PE5 |
| GPIO | Output | SYS_USER_LED3 | PE4 |
| GPIO | Output | SYS_USER_LED4 | PG10 |
| GPIO | Input | BUT_USER1 | PC12 |
| GPIO | Input | BUT_USER2 | PG3 |
프로젝트에서 Cube MX 를 실행한다.

실행된 Cube MX 에서 다음의 핀을 Input/Output 으로 설정한다.

Input/Output 설정방법

LED 의 초기 상태값(꺼짐) 을 만들기 위하여 Configuration 설정을 다음과 같이 High로 설정한다.

설정을 마쳤으면 GENERATE Code 버튼을 누른다.

코드 생성중…

자신의 입맛에 맞게 버튼을 누르자.

hw 폴더에 driver 폴더를 생성 후, button.c / button.h / led.c / led.h 파일을 생성한다.

hw / driver 에 Add/remove include path… 를 누른다.

OK 버튼을 누른다.

코드 작성
Def.h
#include "def.h" // LED 포트 정의 #define _DEF_LED1 0 #define _DEF_LED2 1 #define _DEF_LED3 2 #define _DEF_LED4 3 // Button 포트 정의 추가 #define _DEF_BUTTON1 0 #define _DEF_BUTTON2 1

led.h
#include "hw_def.h" #define LED_MAX_CH 4 void ledInit(void); void ledOn(uint8_t ch); void ledOff(uint8_t ch); void ledToggle(uint8_t ch);

button.h
#include "hw_def.h" #define BUTTON_MAX_CH 2 void buttonInit(void); bool buttonGetPressed(uint8_t ch);

led.c
#include "led.h"
typedef struct
{
GPIO_TypeDef *GPIOx;
uint16_t GPIO_Pin;
GPIO_PinState on_state;
GPIO_PinState off_state;
} led_tbl_t;
led_tbl_t led_tbl[LED_MAX_CH] =
{
{GPIOG, GPIO_PIN_12, GPIO_PIN_RESET, GPIO_PIN_SET},
{GPIOE, GPIO_PIN_5, GPIO_PIN_RESET, GPIO_PIN_SET},
{GPIOE, GPIO_PIN_4, GPIO_PIN_RESET, GPIO_PIN_SET},
{GPIOG, GPIO_PIN_12, GPIO_PIN_RESET, GPIO_PIN_SET},
};
void ledInit(void)
{
uint32_t i;
for (i=0; i<LED_MAX_CH; i++){
ledOff(i);
}
}
void ledOn(uint8_t ch){
HAL_GPIO_WritePin(led_tbl[ch].GPIOx, led_tbl[ch].GPIO_Pin, led_tbl[ch].on_state);
}
void ledOff(uint8_t ch){
HAL_GPIO_WritePin(led_tbl[ch].GPIOx, led_tbl[ch].GPIO_Pin, led_tbl[ch].off_state);
}
void ledToggle(uint8_t ch){
HAL_GPIO_TogglePin(led_tbl[ch].GPIOx, led_tbl[ch].GPIO_Pin);
}

button.c
#include "button.h"
typedef struct
{
GPIO_TypeDef *GPIOx;
uint16_t GPIO_Pin;
GPIO_PinState on_state;
} button_tbl_t;
button_tbl_t button_tbl[BUTTON_MAX_CH] =
{
{GPIOG, GPIO_PIN_3, GPIO_PIN_SET},
{GPIOC, GPIO_PIN_3, GPIO_PIN_SET},
};
void buttonInit(void){
}
bool buttonGetPressed(uint8_t ch)
{
GPIO_PinState button_state;
button_state = HAL_GPIO_ReadPin(button_tbl[ch].GPIOx, button_tbl[ch].GPIO_Pin);
if(button_state == button_tbl[ch].on_state)
{
return true;
} else {
return false;
}
}

hw.h
#include "led.h" #include "button.h"

hw.c
ledInit(); buttonInit();

ap.h

ap.h
if(buttonGetPressed(_DEF_BUTTON1)==true){
ledOn(_DEF_LED1);
} else {
ledOff(_DEF_LED1);
}
if(buttonGetPressed(_DEF_BUTTON2)==true){
ledOn(_DEF_LED2);
} else {
ledOff(_DEF_LED2);
}
다운로드는 여기 버튼을 누르면 다운로드 된다…
