STM32
STM32 LED 버튼 제어, flower 동작
오버헤드프레스
2023. 6. 7. 17:59
LED.C 코드
#include "led.h"
#include "button.h"
void led_main(void);
void led_all_on(void);
void led_all_off(void);
void led_on_up(void);
void led_on_down(void);
void led_keep_on_up(void);
void led_keep_on_down(void);
void button0_led_all_on_off(void);
void button0_led_all_on_off(void)
{
static int button0_count=0; //static으로 하면 전역변수처럼 동작한다.
//한번 정확히 눌렀다 뗀 상태이면
if(get_button(BUTTON0_GPIO_Port, BUTTON0_Pin, 0) == BUTTON_PRESS)
{
button0_count++;
button0_count %= 2;
if(button0_count)
{
led_all_on();
}
else
{
led_all_off();
}
}
}
void led_main(void)
{
while(1)
{
button0_led_all_on_off();
}
}
BUTTON.C 코드
#include "button.h"
//초기 버튼 상태
char button_status[BUTTON_NUMBER] =
{BUTTON_RELEASE, BUTTON_RELEASE, BUTTON_RELEASE};
//gpio, pin, 버튼 상태
int get_button(GPIO_TypeDef *GPIO, uint16_t GPIO_PIN, uint8_t button_number)
{
unsigned char curr_state;
curr_state = HAL_GPIO_ReadPin(GPIO, GPIO_PIN); //p : 0 , r : 1
//버튼이 눌려졌으나 처음 눌려진 상태
if(curr_state == BUTTON_PRESS && button_status[button_number] == BUTTON_RELEASE)
{
HAL_Delay(80); //노이즈가 지나가기를 기다린다.
button_status[button_number] = curr_state; //현재의 버튼 상태 저장
return BUTTON_RELEASE; //버튼이 눌려진 상태이나 noise상태이다.
}
else if(curr_state == BUTTON_RELEASE && button_status[button_number]==BUTTON_PRESS)
{
button_status[button_number] = BUTTON_RELEASE;
return BUTTON_PRESS; //버튼을 1번 눌렀다 뗀 상태로 인정한다.
}
return BUTTON_RELEASE;
}
BUTTON.H 코드
#include "main.h" //for HAL GPIO handling
#define BUTTON_PRESS 0 // 버튼을 누른 상태 : 0 active low : pull-up
#define BUTTON_RELEASE 1 // 버튼을 뗀 상태 : 1
#define BUTTON_NUMBER 3 //버튼 갯수 : 3
//gpio, pin, 버튼 상태
int get_button(GPIO_TypeDef *GPIO, uint16_t GPIO_PIN, uint8_t button_number);
FLOWER 동작을 위한 코드(지금까지 배운 코드 포함)
int button2_count = 0;
void button2_led_flower_on(void)
{
if(get_button(BUTTON2_GPIO_Port, BUTTON2_Pin, 0) == BUTTON_PRESS)
{
button2_count++;
button2_count %= 7;
if(button2_count == 1)
{
led_all_on();
HAL_Delay(200);
led_all_off();
}
else if(button2_count == 2)
{
led_on_up();
led_all_off();
}
else if(button2_count == 3)
{
led_on_down();
led_all_off();
}
else if(button2_count == 4)
{
led_keep_on_up();
led_all_off();
}
else if(button2_count == 5)
{
led_keep_on_down();
led_all_off();
}
else if(button2_count == 6)
{
flower_on();
flower_off();
}
else if(button2_count == 7)
{
led_all_on();
led_all_off();
}
}
}
void flower_on(void)
{
unsigned char led = 0;
for(int i=0; i<4; i++)
{
led |= (0x10 << i) | (0x08 >> i);
HAL_GPIO_WritePin(GPIOB, led, 1);
HAL_Delay(200);
}
}
void flower_off(void)
{
unsigned char led = 0;
led_all_on();
HAL_Delay(200);
for(int i=0; i<4; i++)
{
led |= (0x01 << i) | (0x80 >> i);
HAL_GPIO_WritePin(GPIOB, led, 0);
HAL_Delay(200);
}
}
정상 동작 확인