STM32 Programming from Scratch: Timer Input Capture

   In this tutorial you can learn how  to make a project for STM32 microcontroller using CMSIS and after that  how to write a  code for Timer  input capture to read a pulse of given frequency and duty cycle and measure it.

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 TIMER_TypeDef *TIMER;

Assign the address of  GPIOA and RCC to respective pointers.

clock=RCC;
GPIO=GPIOA;
TIMER=TIM1;

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<<11);//Timer1 clock is enabled

Initialize the GPIO registers also.

GPIO->MODER &=~(1U<<16);
GPIO->OSPEEDR |=(1U<<16)|(1U<<17);
GPIO->AFR[1] &=(1U<<0);//PA8 PIN IS IN ALTERNATE FUNCTION MODE
//IT MEANS YOU ARE SETTING PA8 TO GET INPUT


add code to timer  registers


TIMER->ARR =65535;

TIMER->CCER=(1<<0);

TIMER->CCMR1 |=(1<<0);

TIMER->CR1 |=(1U<<0);//To Run the timer



The complete source code:-



#include "stm32l476xx.h"
RCC_TypeDef *clock;
TIM_TypeDef *TIMER;
GPIO_TypeDef *GPIO;
int main()
{
clock=RCC;
TIMER=TIM1;
GPIO=GPIOA;
clock->CR |=(1U<<16);
while(!((clock->CR)&(1<<17)));
clock->CFGR |=(1U<<1);
        //enable port A
clock->AHB2ENR |=(1U<<0);
        // enable Timer 1 clock
clock->APB2ENR |=(1<<11);
//GPIO ALTERNATE FUNCTION MODE
GPIO->MODER &=~(1U<<16);
        GPIO->OSPEEDR |=(1U<<16)|(1U<<17);
        GPIO->AFR[1] &=(1U<<0);

//Assign values to TIMER BASIC REGISTERS
TIMER->ARR =65535;

        TIMER->CCER=(1<<0);

        TIMER->CCMR1 |=(1<<0);

        TIMER->CR1 |=(1U<<0);//To Run the timer

while(1)
{
}
}
This code will  capture pulse of required frequency on PA8 pin .

Note:This code will work for all STM32 microcontrollers with change in registers value.Refer your microcontroller's  reference manual and datasheet.This code have been tested for STM32L476RG nucleo board.


Comments