2020-08-12 09:43 PM
I want to blink a LED and I have written this code:
#include "stm32f10x.h"
int main()
{
// initialize the clock for Port C
RCC->APB2ENR |= (1<<4); // enable clock for GPIO C ( check it on memory and bus architecture)
// set pin 9 of GPIOC to output mode
GPIOC->CRH |= ((1<<4)|(1<<5)); // PC9 pin will be used as an Output at max speed = 50 MHz
GPIOC->CRH &= (unsigned int)~((1<<6)|(1<<7)); // output mode in push-pull configuration (set 11 to CNF bits), that is, General Purpose Output
int i;
while(1)
{
for(i=0;i<=5000000;i++);
GPIOC->BSRR = (1<<9);
for(i=0;i<=5000000;i++);
GPIOC->BSRR = (1<<(9+16));
}
}
// keil requires you to leave an extra line after the last bracket
The output for PC9 only yields a weird 5MHz pulse for any possible value I write in the comparison for loop field. At last, the LED turns on but as I'm using 8MHz for system clock, it should blink at a rate I would be able to see (i<=5000000 gives a 625ms switching period).
So, am I missing any register setting or whatnot?
Thank you in advance.
2020-08-12 10:01 PM
Qualify i as volatile.
Decrease the constant, roughly 10x.
Single-step in disasm both versions to see the difference.
>using 8MHz for system clock
Are you sure?
JW
2020-08-12 10:16 PM
Hi JW, it worked. I qualified i as volatile and reduced the constant, but why did that work? I have seen other people doing exactly like that (but using STM32F103C8T6) and it did work.
Yet I still do not understand 2 other situations:
why can I not watch the variable while debugging (<cannot evaluate> for both int or volatile int types) ?
and why is it not 8 MHz for system frequency?
2020-08-12 10:55 PM
https://blog.regehr.org/archives/28
Without volatile your loop is doing nothing useful and compiler is not required to keep it. That happens when some optimization is turned on and that is also the reason you cannot watch some variables.
2020-08-12 11:09 PM
Just a remark: there are predefined constants which make your code more readable like (for a different chip):
RCC->AHBENR |= RCC_AHBENR_GPIOBEN; // GPIO port B clock enable
GPIOB->MODER |= GPIO_MODER_MODER3_0; // mode 01: GPIO output
GPIOB->MODER &= ~GPIO_MODER_MODER3_1; // mode 01: GPIO output
GPIOB->OTYPER &= ~GPIO_OTYPER_OT_3; // type: push-pull
GPIOB->OSPEEDR &= ~GPIO_OSPEEDER_OSPEEDR3; // speed 00: low speed
GPIOB->PUPDR &= ~GPIO_PUPDR_PUPDR3; // no pull-up, no pull-down
for(;;) {
GPIOB->BSRR = GPIO_BSRR_BS_3; // Bit Set
delay();
GPIOB->BSRR = GPIO_BSRR_BR_3; // Bit Reset
delay();
}
2020-08-12 11:49 PM
> and why is it not 8 MHz for system frequency?
Some code in startup (SystemInit() or similar) which changes the RCC settings?
JW
2020-08-13 05:50 AM
I suggest implementing a version of HAL_Delay that works if you need a delay functionality.