I am trying to setup the SPI. I followed the logic from other tutorials but with no success. Can someone point me in the right direction?

void spi_setup(void) {

    RCC_AHBENR |= _BV(17); //IOPAEN
    RCC_APB2ENR |= _BV(12); //SPI1EN

    GPIOA_OSPEED |= 0x11<<7 | 0x11<<6 | 0x11<<5; //GPIO CLOCK SPEED
    GPIOA_MODER |= _BV(5*2+1)/*AFM*/ | _BV(6*2+1)/*AFM*/ | _BV(7*2+1)/*AFM*/;
    GPIOA_AFRL |= 0;
    //GPIOA_OTYPER = _BV(7) | _BV(6) | _BV(5); //output OPEN-DRAIN
    //GPIOA_PUPDR |= _BV(7*2+1)/*pull DOWN*/ | _BV(6*2+1)/*pull DOWN*/ | _BV(5*2+1)/*pull DOWN*/;

    SPI1_CR2 |= 0x111<<8/*8B data size*/;
    SPI1_CR1 = _BV(9)/*Soft slave man*/ | _BV(6)/*SPI Enable*/| (0x0<<3)/*BaudRate*/ | _BV(2)/*Master*/ | _BV(0)/*Clock Polarity*/;

void spi_tx (uint8_t send) {

    while ( SPI1_SR & _BV(7) ) {} /*while BUSY WAIT */

    SPI1_DR = send;

This is an example of how to not write code:

RCC_APB2ENR |= _BV(12); //SPI1EN

You have to remember what bit 12 means, an ususally end up looking in the manual to check. Repeating this for all the other bits takes too much time and errors are very difficult to spot.

Thats why there is a STM32F0xx standard peripherals library. Using this you can write much more readable code:

RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);

I would also expect to find some example code for SPI on the vendors website.


You must use ST snippets package for STM32F0, dont use standard peripherals library like above. This library do not work with STM32F0xx, this library is prepared only for STM32f1xx-4xx chips.

  • \$\begingroup\$ While it is possible there are specific ways in which this code erroneously targets a different STM32 family than the F0 in use, your basic assertion is entirely incorrect as there is in fact a version of the STM32 standard peripherals library for the F0 - in fact there's a link to it in the other answer here. Further, F1-F4 do not have a uniform version - rather, each family generally has its own. \$\endgroup\$ – Chris Stratton Nov 15 '15 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.