Embedded System/STM32

[Cortex-M3] 겁나빠른 GPIO 사용하기

임베지수 2017. 4. 2. 14:52

(http://embejied.tistory.com/82에서 GPIO 사용하는 방법에 대해 설명했었다. 하지만 GPIO의 속도가 매우 느리다. 왜냐하면 함수를 사용하기 때문에 느린것이다. 물론 이것도 빠르긴하지만 GPIO속도를 50MHz로 설정한 의미가 없다... while문에서 딜레이 없이 토글만 시켜도 1Mhz정도 밖에 안나온다. 이를 해결하려면 레지스터에 바로 접근하면 된다. 어떻게 하는 것일까...

 

처음 GPIO 초기화 소스는 똑같다. 하지만 main에서 사용할 때가 조금 다르다. GPIO_Write()등의 함수를 사용하지 않고

BSRR, BRR 레지스터를 사용하는 것이다.

 

아래 소스를 참고하자.

#include "stm32f10x.h"

void init_port()
{    
    GPIO_InitTypeDef PORTA;
    GPIO_InitTypeDef PORTB;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
    
    PORTA.GPIO_Pin = 0x0001;
    PORTA.GPIO_Mode = GPIO_Mode_Out_PP;
    PORTA.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &PORTA);
    
    PORTB.GPIO_Pin = 0x0001;
    PORTB.GPIO_Mode = GPIO_Mode_Out_PP;
    PORTB.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &PORTB);    
}

int main()
{
    unsigned int i=0;

    init_port();
    
    while(1)
    {
        GPIOA->BRR = GPIO_Pin_0;  // PA0 OFF
        GPIOB->BSRR = GPIO_Pin_0; // PB0 ON
        for(i=0; i<1000000; i++); // delay
        
        GPIOB->BRR = GPIO_Pin_0;  // PB0 OFF
        GPIOA->BSRR = GPIO_Pin_0; // PA0 ON
        for(i=0; i<1000000; i++); // delay
    }
}

우왕 간단하다. 끝.

 

※ 물론 컴파일 옵션에서 속도최적화도 해주어야 겁나 빨라짐