Search code examples
cembeddedstm32cortex-m

Enabling an output port in stm32f103c8t6 Blue Pill


I'm trying to enable the PC13 in the Blue Pill (stm32f103c8t6) which is connected to an LED, not sure if it is active low or active high so i tried both still doesn't work.

RCC->APB2ENR |= 0x10;
is used for enabling the clock in Port C.

enter image description here


GPIOC->CRH = (GPIOC->CRH & 0xFF0FFFFF) | 0x00100000;
is used to configure the port C to be in Output mode and Push-Pull.

enter image description here


GPIOC->ODR &= !(1<<13); is used to drive the C13 pin to LOW.

The whole code:

#include "stm32f10x.h"

int main(){
    RCC->APB2ENR |= 0x10;
    GPIOC->CRH = (GPIOC->CRH & 0xFF0FFFFF) | 0x00100000;  
    while(1) {
        GPIOC->ODR = ~(1<<13);//if it is Active Low
        for (int i = 0; i < 1000000; ++i) __asm__("nop");
        GPIOC->ODR |= 1<<13; //if it is Active High
        for (int i = 0; i <  500000; ++i) __asm__("nop");
    }

}

Edit :
After some investigation, i discovered that the code is working perfectly if run a debugging session, could it be a software problem? or the code for debugging sets things i didn't ? and as i said, I'm using uVision to compile and flash.


Solution

  • If you are running Keil as you've said in your comments than it is quite certain that you are using the ST HAL. As such you should use it.

    Use this to enable the GPIOC clock

    __GPIOC_CLK_ENABLE();
    

    It also sounds like you haven't enabled another clock. I can't figure out at this time which one it is but it is probably one high up in the chain. (This probably happens because you enabled the clock using APB2ENR instead of the macro)

    Another solution to figure it out would be to use STM32CubeMX it is a multiplatform tool proved by ST to create base initialized projects for several IDEs.

    Download and run it, create a project for your MCU, add the pin you want to drive as an output and generate a Keil project which should compile and run. If it works you can then reverse engineer the steps that STM32CubeMX took to create working code.


    Your underlying problem is that you haven't enabled reset and run in the configuration. As such after programming the board needs to be reset before the newly flashed code will run. Starting the debugger does this.

    configuration window with reset and run

    This configuration is found inside the utilities->settings menu. (ignore the red marker, I couldn't capture the image myself and as such got it from the internet)

    enter image description here