STM32 Programming from scratch:SPI Master

 In this tutorial you can learn how  to make a project for STM32 microcontroller using CMSIS and after that   write a  code for SPI Master .You will be able to send data to slave from master by this code

Requirement for this project:-

Software:-
  • Keil uvision5
Hardware used:-
  • STM32L476 Nucleo board(any other nucleo board from ST will also work)
  • USB Port of laptop/desktop
Steps to make a new project in keil:-

The coding part:-

1)Include the header file of microcontroller in main.c

In main  write the relevant code:-

start with declaring the declaring the structure pointer to RCC_TypeDef  and pointer to GPIO_TypeDef

static RCC_TypeDef  *clock;

static GPIO_TypeDef  *GPIO;

static SPI_TypeDef  *SPI;

Assign the address of  GPIOA and RCC to respective pointers.

clock=RCC;
GPIO=GPIOA;
SPI=SPI1;

Select the clock source of microcontroller unit.I am using HSE in this code


clock->CR |=(1<<16);//clock source is on board 8 MHz crytal



Initialise the other required register also.

while(!((clock->CR)&(1<<17)));//Wait till HSERDY FLAG IS SET
clock->CFGR &=(1U<<1);


clock->AHB2ENR|=(1U<<1);//clock of port A is enabled
 clock->APB2ENR |=(1U<<12);//SPI1 clock is enabled

Initialize the GPIO registers also.

GPIO->MODER &=~(1U<<16);
GPIO->MODER &=~((1U<<10)|(1U<<14)|(1U<<8)|(1U<<12));
GPIO->AFR[1] |=((1U<<20)|(1U<<22)|(1U<<28)|(1U<<30)|(1U<<16)|(1U<<18)|(1U<<24)|((1U<<26));//SET  ALTERNATE FUNCTION MODE for all 4 pins

//SCLK,MOSI,MISO and NSS



Add code to initialize spi registers


SPI->CR1 |=(1U<<14)|(1U<<9);//OUTPUT ENABLE IN BIDIRECTIONAL MODE

SPI->CR1 |=(1U<<2);//MASTER MODE OF SPI

SPI->CR2 |=(1U<<8)|(1U<<9)|(1U<<10);//

SPI->CR2 |=(1U<<2);

SPI->CR2 |=(1U<<3);//NSSP PULSE MANAGEMENT

SPI->SR1 |=(1U<<1);//TRANSMIT BUFFER EMPTY

SPI->CR1 |=(1U<<6);//SPI1 ENABLE

while(1){

SPI1->DR1 ='A';//Assigning data to data regsiter
while(!((SPI1->SR1)&(1U<<1)))//Wait till data is sent
}

}

 

Comments