Embedded MCU's Getting Started and Peripheral Coding STM32F1 Tech

UART Peripheral in STM32F103

Overview

So, welcome to the series of STMicroelectronics, STM32F103 microcontroller coding series, in which we are covering its various peripheral coding.

As covered in the last blog’s we have covered various peripherals of STM32F103 MCU and understand their working, in this blog we’ll be covering one of those special or alternate functions of the GPIO pins i.e. the UART(USART) functionality of these pins. Before discussing UART we’ll be discussing different types of communication.

Other blogs to explore:

  1. ADC(Analog To Digital Converter) in STM32F103 – gettobyte
  2. PWM on STM32F103 – gettobyte
  3. GPIO Peripheral in STM32F103 MCU – gettobyte

Types of Serial Communication

Other Serial Communication Peripherals and protocols

SPI in STM32F103
I2C in STM32F103

UART Theory

UART Serial Communication

So UART is a type of serial communication protocol in which data is sent serially bit by bit over a single wire both in synchronous and asynchronous mode. In which each frame comprises of a start bit , a stop bit and 8 data bits with an exception of parity bits.

Types of communication in USART (serial) communication: –

  • Synchronous – Clock is transmitted with the data.
  • Asynchronous – Their is no clock when the data is send, instead data in itself has start and stop bits for indicating when data is started and ended.

Hence the whole module is called USART(Universal Synchronous Asynchronous Receiver Transmitter)

Transmission MODES in USART

DUPLEX- The data can be transmitted and received.

SIMPLEX- The data can only be transmitted or received.

Fig-5: Simplex communication

Duplex can be further divided into: –

HALF DUPLEX-In this data can only be transmitted in only one way.

Fig-6: Half Duplex Communication

FULL DUPLEX- In this data can be transmitted both ways at a time.

Fig-7:Full Duplex Communication

HOW A SINGLE CHARACTER IS TRANSMITTED IN UART PROTOCOL

 

ASCII table is universal table, in which every English alphabet, mathematical number and different signs have been mapped to binary number in the hex and decimal format. Like in the below table, if u take character A, it is mapped to value of 0x41 which is in binary is: 01000001. That is what is transmitted as bits in word length in UART One Frame.

ASCII Table

UART CONFIGURATION PARAMETERS

Specifies the agree upon clock speed of the communication of the bits between transmitter or receiver.

Specifies the end of transmission .They maybe 1 bit or 2 bits i.e when the transmission ends the stop bits maybe 1 or 11

They state the start of transmission and are 1 bit

This indicates the parity mode whether odd or even . This is used to check for errors

Specifies the mode enable by the specified pin which is TX, RX or TX and RX.

Specifies the no of data bits transmitted or received .The value varies between 8 or 9 bits

Is a strategy for communication between slow and fast devices without loss of data.This can either be enabled or disabled. 

BLE Module interfacing with STM32F103
GPS Module interfacing with STM32F103
WiFi Module interfacing with STM32F103
GSM Module interfacing with STM32F103

UART Features in STM32F103

USART INSTANCES in STM32F103

There are 3 usart instances USART1 , USART2 and USART3.

  • To configure USART1 the pins the pin PA9 will be TX and pin PA10 will be RX
  • In case of USART2 the pin PA2 will be TX and PA3 will be RX 
  • For USART 3 the RX and TX will be PB11 and PB10 respectively.

  • The USART supports LIN (local interconnection network), Smartcard Protocol and IrDA (infrared data association) SIR ENDEC specifications, and modem operations (CTS/RTS).
  • Smartcard is a single wire half duplex communication protocol.The smartcard mode can be selected by setting the SCEN bit in the USART_CR3 register while LINEN bit in the USART_CR2 register,  HDSEL and IREN bits in the USART_CR3 register are kept in clear mode.The CLKEN bit may be set in order to provide a clock to the smartcard. 
  • The IrDA mode is selected by setting the IREN bit in the USART_CR3 register. In IrDA mode LINEN, STOP and CLKEN bits in the USART_CR2 register,  SCEN and HDSEL bits in the USART_CR3 register are cleared.
  • The LIN mode is selected by setting the LINEN bit in the USART_CR2 register. The STOP[1:0], CLKEN in the USART_CR2 register  SCEN, HDSEL and IREN in the USART_CR3 register are cleared for the selection of LIN mode

USART MODE CONFIGURATIONS TABLE

 

How to configure the UART peripheral pin in STM32F103?

We would be using STM32 HAL and STM32CubeIDE for using the UART peripheral in STM32F103 in this blog tutorial series.

Configurations in STM32CubeIDE for STM32F103

Fig-8: Configuring as TX
Fig-9:Configuring as RX
Fig-10:Configuring Parameters
Fig-11:Configuring Peripheral Settings

STM32 HAL Peripheral Data Handling API types

  1. Non Interrupt Based(Polling type)
  2. Interrupt Based
  3. DMA Based (Uses DMA and Interrupts)

STM32 HAL SDK Files for UART

Stm32f1xx_hal_msp.c consists of void HAL_UART_MspInit which is used to initialize the gpio peripheral and configure hardware resources to act as UART module

Stm32f1xx_hal_uart.h consists of UART init structure definition which consists of various parameters such as parity bits , stop bits,baud rate, word length, mode, Hwflowctl etc . It also consists of various macro definition , enum and error types.

Stm32f1xx_hal_uart.c consists of Uart macros , configuration and initialization of hardware resources configuring functions

 

DEMO EXERCISE

CONVERTING THE RECEIVED DATA INTO ALL CAPITAL LETTERS

				
					  uint8_t conv_to_caps(uint8_t data);
  uint8_t receiveddat;
  uint8_t datbuffer[100];
  uint32_t count=0;
  char *data="The application is running \r\n";
  uint32_t lengdat = strlen(data);
       HAL_UART_Transmit(&huart2,(uint8_t*)data,lengdat,HAL_MAX_DELAY);
  

  
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
	  HAL_UART_Receive (&huart2, &receiveddat, 1, HAL_MAX_DELAY);/*STEP 2*/
	    if(receiveddat == '\r'){
	    	break;
	    }
	    else{
	    	datbuffer[count++]= conv_to_caps(receiveddat);/*STEP 4*/
	    }
    /* USER CODE BEGIN 3 */
  
  /* USER CODE END 3 */
}
  datbuffer[count++]='\r';
  HAL_UART_Transmit(&huart2,datbuffer,count,HAL_MAX_DELAY);/*STEP 5*/
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2; /*STEP 1*/
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
uint8_t conv_to_caps(uint8_t data){    /*STEP 3*/
	if(data >='a' && data<= 'z'){
		data = data - ('a'-'A');
		
	}
	return data;
}

				
			

NOTE- The above code could be implemented using printf functionality with using IO_Putchar function

PRINT SINGLE CHARACTER

				
					uint8_t test[1]="H";

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_UART_Transmit(&huart1, test, sizeof(test), 25);

}

				
			

PRINT STRING

				
					#include 
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */
void uprintf(char *str){
	HAL_UART_Transmit(&huart1, (uint8_t *)str, strlen(str), 25);
}
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */
while (1)
  {
    /* USER CODE END WHILE */
     uprintf("PRATYUSH KAUSHIK\n");
     HAL_Delay(1000);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

				
			

INT X++

				
					#include "main.h"
#include 
#include 
/* Private includes ----------------------------------------------------------*/\
char buffer[32]={0};
uint8_t count=0;
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */
void uprintf(char *str){
	HAL_UART_Transmit(&huart1, (uint8_t *)str, strlen(str), 25);
}
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */


/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */



  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	 count++;
    /* USER CODE END WHILE */
	 sprintf(buffer, "count :%d\n", count);
	 uprintf(buffer);
	 HAL_Delay(1000);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

				
			

PRINT FLOATING TYPE

				
					#include 
#include 
/* Private includes ----------------------------------------------------------*/\
char buffer[32]={0};
uint8_t count=0;
float pi=3.14;
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */
void uprintf(char *str){
	HAL_UART_Transmit(&huart1, (uint8_t *)str, strlen(str), 25);
}
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */


/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */



  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	
    /* USER CODE END WHILE */
	 sprintf(buffer, "Float Val : %f\n", pi);
	 uprintf(buffer);
	 HAL_Delay(1000);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

				
			

HAL APIs and other function involved

  • HAL_StatusTypeDef HAL_UART_Init (UART_HandleTypeDef * huart)
  • HAL_StatusTypeDef HAL_UART_Transmit (UART_HandleTypeDef * huart, uint8_t * pData, uint16_t Size, uint32_t Timeout) 
  • HAL_StatusTypeDef HAL_UART_Receive (UART_HandleTypeDef * huart, uint8_t * pData, uint16_t Size, uint32_t Timeout )
  • static void MX_USART2_UART_Init(void)
  • void HAL_UART_MspInit(UART_HandleTypeDef* huart)

FUNCTION NAME

                  HAL_StatusTypeDef HAL_UART_Init (UART_HandleTypeDef * huart)

FUNCTION DESCRIPTION

                  Initializes the UART port according to the given parameters in UART_InitTypeDef and create the associated handle

PARAMETERS 

     UART_HandleTypeDef * huart – takes in pointer to the structure  UART_HandleTypeDef that helps in configuring the port according to parameters specified by the UART module

RETURN TYPE

    NONE

FUNCTION NAME

                   HAL_StatusTypeDef HAL_UART_Transmit (UART_HandleTypeDef * huart, uint8_t * pData, uint16_t Size, uint32_t Timeout)

FUNCTION DESCRIPTION

  This API is used for sending the data in blocking mode i.e the CPU stops the operation until the data is transferred

PARAMETERS

    UART_HandleTypeDef * huart – The pointer to the structure  UART_HandleTypeDef that contains the information of configuration of the uart module

    uint8_t * pData – The pointer to the data buffer that stores the data

    uint16_t Size – The size of the data to be sent(size of array or size of the string)

    uint32_t Timeout – The time for which the blocking mode prevails

RETURN TYPE

   HAL- STATUS

				
					USAGE
    char *data="Hello from stm32 \r\n";
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
       uint32_t lengdat = strlen(data);
       HAL_UART_Transmit(&huart2,(uint8_t*)data,lengdat,HAL_MAX_DELAY);
    
    /* USER CODE BEGIN 3 */
  }

				
			

FUNCTION NAME

   HAL_StatusTypeDef HAL_UART_Receive (UART_HandleTypeDef * huart, uint8_t * pData, uint16_t Size, uint32_t Timeout)

    FUNCTION DESCRIPTION

Receives the specified amount of data in blocking mode

   PARAMETERS

    UART_HandleTypeDef * huart – The pointer to the structure  UART_HandleTypeDef that contains the information of configuration of the uart module

    uint8_t * pData – The pointer to the data buffer that stores the data

    uint16_t Size – The size of the data to be sent(size of array or size of the string)

    uint32_t Timeout – The time for which the blocking mode prevails

   RETURN TYPE

   HAL- STATUS

				
					uint8_t receiveddat;
  uint8_t datbuffer[100];
  uint32_t count=0;
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
       if(receiveddat=='\r’)
    	   break;
       }
              else{
       HAL_UART_Receive (&huart2, &receiveddat, 1, HAL_MAX_DELAY);
	  datbuffer[count++]=receiveddat;
       }
       
    
      }


				
			

FUNCTION NAME

        static void MX_USART2_UART_Init(void)

    FUNCTION DESCRIPTION

  Initializes the uart module according to parameters such as baudrate, wordlength, stopbits etc

   PARAMETERS

     NONE

  RETURN TYPE

     NONE

				
					static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

				
			

FUNCTION NAME

   void HAL_UART_MspInit(UART_HandleTypeDef* huart)

FUNCTION DESCRIPTION 

  Initialize the microcontroller support package 

PARAMETERS

  UART_HandleTypeDef* huart- Pointer to the structure UART_HandleTypeDef that specifies all the configuration of the uart module

				
					void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(huart->Instance==USART2)
  {
  /* USER CODE BEGIN USART2_MspInit 0 */

  /* USER CODE END USART2_MspInit 0 */
    /* Peripheral clock enable */
    __HAL_RCC_USART2_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART2 GPIO Configuration
    PA2     ------> USART2_TX
    PA3     ------> USART2_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_2;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

				
			

Conclusion

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

Author

What is Microcontroller Technology?

Brief history of Microcontroller Microcontroller is an innovative technology that has revolutionize the world and made the electronic items so much feasible for us. Though microcontrollers have been in world since 1960’s. Its been around 60 years since the invention of Microcontroller technology and their are more then x amount of microcontroller being deployed right now in world. Lets explore and go back to history of microcontroller’s: What are Microcontrollers is an electronic chip which is designed in a way to do general tasks till eternity The life cycle of Microcontroller’s Microcontroller is designed from transistors, millions and millions and even billions of transistors are minitirised into small size, to form building blocks of MCU, and these building blocks give them ability to control anything. The building blocks of MCU are: CPU, Memory and Peripherals. We will dive into these blocks after couple of minutes. The designing of these transistors is an art and science behind the chip designing. This art of technology is called as VLSI( Very Large Scale Integration). And Once the designing is done then these Chips are fabricated/manufactured to give us a final by product that is physical MCU chip. And This part is done by fabrication companies like TSMC. And after that fabrication, the packaging/assemble of integrated chip happens so that these millions and millions of transistors which are minitiasuered are enabled for practical usage in electronic devices. And after that programming on these MCU and extra circuietry around these MCU’s is developed to make the MCU do any specific task till eternity. These part are referred as Embedded Systems, in which software and hardware arounf the microcontroller is developed to make it use in final end product. Part of Software development for Microcontrolleris called Embedded Software Development and part of Hardware development for MCU is called Embedded Hardware Development. In this video and cahpter we will just get ourselves stick to microcontroller technology, and focus on what things are involved for learning and using microcontroller. Though their are many topics and technologies which can be deep dive, which we will do in separate videos. Building blocks of Microcontroller chip are Microcontroller chips have 3 building block, first is CPU, second is Memory and third is peripherals. For better understanding take the analogy of microcontroller with human body. Just like their is human body, same way their is microcontroller. In human body we have brain which does all the processing, calculations and thinking. In the case of microcontroller, CPU does all that. Then in human body we have body parts to interact with outside world, same way microcontroller have different peripherals to interact with outside world. We humans have memory/yadash based on which we do the work and do the tasks. How to sit, how to walk, how to use legs, how to use different body parents, and all these things are feed in our memory, same way microcontrollers have memory, into which instructions are written on how to use its different peripherals and how to control those peripherals and what to do when some data comes from those peripherals. Now lets just deep dive into these functional blocks in more technical understadning and learning. CPU CPU stands for Central Processing Unit, it is an integral part of microcontroller which does all the hardcore computing work. computing work in terms of electronic chip means: addition, subtraction, multiplication, division of electronic data. How fast this can be done and level of complex calculations it can do. CPU does the computing work, by a set of basic rules on how a CPU should work. These set of rules are called as Instruction Set Architecture(ISA). Their are 2 most popular types of ISA: RISC( Reduced Instruction Set Computer) CISC(Complex Instruction Set Computer) In Current modern world, RISC architecture based CPUs and microcontroller are what is widely used and adaptoped. Examples of RISC is ARM CPU that we see in Apple MAC book the M1 chip. another example is RISC-5 CPU, that we can see in Vega processor, which is Indias first indegenoious CPU designed by xyz organization Examples of CISC is Intel 4004, which is world’s first commercially avialable CPU launched in 1971. Another is x86 CPU, most desktops and laptops sold are based on x86 CPU. Ther terminology which we hear intel I5 processor and all they all are part os these CPU’s. Often CPU word/terminology is used interchanagible with processor or core. So whereever we mention, processor/core or CPU words they mean same thing. Another important factor on which CPU computing work matters is bit size of CPU. Meaning how much size of data CPU can execute at a time. We measure this thing in bits unit. So their are 8 bits, 16 bits and 32 bits CPU’s. In Which 8 bit CPU means it can at a time can execute data of 8 bit length. 16 and 32 bit CPU means they can execute data of 16 bit and 32 bit length. Now as the bit size of CPU increases, it means more pwoerfull and fast tehy are. For now we are not going too much in detail about CPU types, history and its world as that will deviate us from current topic of microcontroller. We will explore in detail about these terminologies in what is microprocessor technology. Peripherals: Peripherals are body parts of Microcontroller, it is peripherals through which micrcontroller interacts with outside world. Their can be more then 20 peripherals in some MCU’s and in some MCU’s their can be just 5 peripherals. Their are some general purpose peripheral which are their in all or most of the MCU’s: which are GPIO, ADC, TIMERS, I2C, SPI, UART. Using these peripherals one can process and control any sensor/module connected to MCU. I2C, SPI and UART are communication protocol via which we can connect almost any sensor/module to MCU. Be it LCD screen, ethernet module, audio devices, wifi modules or any other sensor. And via GPIO, TIMER and ADC peripherals we can sample and

Read More »

FlexTimer peripheral of NXP S32K1xx MCU( S32K144 MCU and ElecronicsV3 Board)

About FlexTimer Peripheral of S32K144 MCU: What is FlexTIMER Peripheral? FlexTimer is a peripheral present in NXP S32K1xx MCU’s, which is used for input capture, output capture, generation of PWM signals and time delays. We are going to focus on PWM signals part and usecase of FTM Peripheral for generating PWM signals. As FTM is a peripheral of MCU, so it has intances and with each instance certain number of MCU pins which are referred as channels. In S32K144 their are 4 instances of FTM and each instance has 8 channels. Instances are abrievted as FTM0, FTM1, FTM2 and FTM3. Each Instance has its own Peripheral registers where the configuration of those instances is done.  Their are number of registers, in FTM peripheral through which its configuration for different features is done and we also get status. We are not going to dive into every register, will mention important registers, as in industry register level coding is not implemented but understanding of registers is what is important. Each Instance has 8 channels, which are reffered as CH0-CH7. So naming convection goes like this: Table showing FTM Instance and Then FTM Channels of that sinstance and all MCU pins which can be used for that channel. For PWM,  FTM Peripheral has following functnalities and features PWM Signal Type: Center Aligned and Edge Aligned PWM Signals: Combine Mode PWM signals in inverted/duplicate PWM Interrupts: Every channel has interrupt source. Interrupt can be generated on counter match or counter overflow. Detection of rising and failing edges of PWM signals: We can configure interrupt generation when counter matches or overflows based on the polaruty of PWM signal. Hardware-Software Trigger: Generation of PWM signals and variation of PWM parameters at the detection of some hardware specific events. Lets say we want to generate PWM pulse only when some ADC readings are taken. So we can configure PWM signal to generate when ADC hardware conversion si done. Fault control and synchronization points.  How FTM peripheral works is, For understanding the ftm peripheral features and functionalities we will understand them via storytelling!!! Story telling in terms of what steps have to be followed to use ftm peripheral and correspondingly covering its different features. We configure the clock values for ftm peripheral, that is whether the ftm peripheral is going to get clock from system clock, fixed clock or external clock and  also configures the prescaler values, to divide the ftm clock if needed. FTM CLOCK CONFIGURATION IS IMPORTANT step as based on this only, parameters of pwm signals are calculated. Their are 3 inputs of clocks for FTM peripheral: either system clock, or crystal oscillator clock( that is fixed clock) or some external clock ( connected to some pin of MCU). After that we configure in which mode FTM peripheral has to be used, whether input capture mode, output capture mode. Output capture mode is what we are going to use. Output capture mode means outputings some digital signals. And Input capture mode means inputting some digital signals. After output capture mode,  which type of pwm signal. These settings are done by setting the values of highlighted bits according to following table. These bits are part of these registers. Based on the mode of ftm peripheral, ftm peripheral will work. As in this module we are learning and focusing on pwm signals, so we highlighted sections of table is what is going to be of our concern.    Edge Aligned Mode Center Aligned Mode Combine Mode(Complementary) Each Instance has 8 channels, so every channel has its own peripheral registers by the name of CnSC. In CnSC register this pwm mode of configuration is done.  After that, we configure the values into counters of FTM. As stated Timer peripheral has 3 counters in it. MAX counter, Variable counter and Threshold counter. In FTM peripheral MAX counter is MOD peripheral register. Value put on this register determines the frequency /period of pwm signal. Variable register is COUNT peripheral register. This counter starts incrementing from 0 once ftm peripheral is enabled or triggered. Threshol Counter we will touch in couple of mins after. For each channel their is register CnV. This register act as Threshold counter for pwm signal coming from corresponding channel or we can say pin of mcu. Value put on this register will determine the duty cycle of the signal as when COUNT counter matches the value of this register, pwm signal state changes according to configured polarity. Now polarity of pwm channel will determine, whether pwm signal would have high to low transition or low to high transition on counter match. The polarity configuration is important as this will determine the duty cycle parameter. So there are 2 things in polarity, state of pwm signal before counter match and state of pwm signal after counter match. Based on polarity configuration, rising or failing edges would be generated on counter match and counter overflows. 6) Another important thing is updates of counter registers and pwm polarity. You see, counter registers like MOD, CnV and COUNT very much control the PWM signal parameters and PWM polarity register bits control the logic levels of pwm signal. Ftm peripheral has feature to configure when these register values should be updated, that is either on software trigger means software will write the Data on the registers and it would be loaded into them. Or hardware trigger that on detection of sone external signal, the values of these registers would be changed. This updation of register is also called as Reload point of counter registers and values in FTM peripheral. If we are using interrupts then interrupt configuration is also done for each indiviual channel for different events. By events we mean counter match or counter overfflow. For every channels of FTM Instance their are bits in x register, If we set these bits then interrupt functionaly would be on for those Channels. When Counter match happens then channel interrupt handlers are fired and when counter oveflow happens then overflow interrupt handler is fired. Overflow interrupt handler is comman

Read More »

PWM Driver of Autosar MCAL Layer

What is PWM Driver? PWM Driver is the library for generating PWM signals via Automotive MCU’s. This Driver is part of Autosar MCAL layer and it is global level RTD standard that is followed by all semiconductor companies to generate the PWM signals using their microcontrollers for automotive applications. This specification describes the API for generating and handling different PWM signals via automotive MCU’s. This software module includes GUI interface for initialization, configuration of PWM channels and peripheral instances. It supports the framework for using advance to basic features which are their with PWM peripherals of different MCU’s through which PWM signals are generated.. Also PWM Driver handles the variation of PWM parameters like  Frequency, Duty Cycle, Timer Period and etc. PWM Driver can handles all the advance features like fault control, synchronization points, hardware trigger, softare control values, complementary PWM signals, DMA/Interrupts for PWM signals. . PWM Driver is built over the peripheral IP layer of the Microcontroller and driving functionalities. Main objectives of this monolithic SPI Handler/Driver are to take the best of each microcontroller features and to allow implementation optimization depending on static configuration to fit as much as possible to ECU needs. Hence, this specification defines selectable levels of functionalities and configurable features to allow the design of a high scalable module that exploits the peculiarities of the microcontroller. What are PWM Signals and how are they generated? Types of PWM Signals: Parameters of PWM Signals: To generate the PWM signals via Automotive MCU’s using Autosar MCAL Layer API’s: At first to configure the MCU pins in PWM peripheral mode via PORT Driver: We can generate the PWM Signals from Microcontroller through different peripherals like Timer Peripheral of the MCU or FlexIO peripheral. So at first selection of MCU pin has to be done from which PWM signal has to be genarted and then configuring that MCU pin in corresponding peripheral mode. After that comes the clock selection and configuration via MCU Driver: MCU Driver is responsible for clock configurations and clock settings of Microcontroller. Setting of systems clock, peripehral clocks all these settings are done by MCU Driver. And for generating the PWM Signals, what clock frequency has been input to it is very crucuial so as to calculate its parameters. After this MCL Driver selection is also important: We can generate PWM signals from Microcontroller via different peripherals. Either Timer based peripheral or FlexIO peripheral. By tradation Timer peripheral is recommended and widely used. But as PWM Driver has been designed with global level coverage, it is also dependent on FlexIO peripheral, so FlexIO peripheral concentric files are generated via MCL Driver. So we will just select the MCL Driver, so that dependent files are included in project. In this course, we will focus on PWM signal generation via Timer peripheral. In our case we will be using NXP S32K144 MCU which has FlexTIMER Peripheral. After all above three will be coming our PWM Driver configuration and selection. That is what is the main moto of the course module. We will understand what all configurations are their in PWM Driver. How PWM Driver works and important API;s of it for generating the PWM Signals. Their would also be use of Platform Module, that is responsible for interrupt settings and configuration. We are going to use Interrupts with PWM Signals to detect the rising and failing edges of PWM signals and do some application specific tasks on those edges. Functional concepts of PWM Driver: Now PWM Driver has general/global functional concepts which are applicable to all automotive MCU’s, which are important to understand and know so as to configure the PWM Driver. Selection of PWM hardware channel: Selection of PWM Channel polarity Selection of PWM IDLE Mode Selection of PWM feature enablement: PWM Signal modes: Apart from the above general functional concepts, the PWM peripheral level concepts of the corresponding Micrcocontroller is also important to understand. These peripheral level functional concepts are different from one MCU to another. As their are different peripherals for generating PWM signals in different MCU’s. But the usage of these concepts is used only at the time of PWM GUI configuration. At the time of writing the embedded application, same set of API’s, chronology and parameters is used. In our case we have ElecronicsV3 Board, which has S32K144 MCU and we are using FlexTIMER peripheral of this MCU. Concepts description with respect to Author: Kunal Gupta

Read More »

FTM PWM Driver API’s of NXP S32K144 MCU

API Name: Ftm_Pwm_Ip_Init() void Ftm_Pwm_Ip_Init(uint8 Instance,const Ftm_Pwm_Ip_UserCfgType * UserCfg) Role: This API initializes the FTM peripheral according to PWM feature.  Author: Kunal Gupta

Read More »

SAR ADC Explained!

Why to learn about SAR ADC? SAR ADC is a standard AUTOSAR opts for. That’s why you see most of the automotive microcontrollers can be observed having SAR ADC and SAR stands for Successive Approximation Register. You can see the below picture which I extracted for verification of this fact. Microcontrollers which are verified: NXP S32K1xx Series NXP MPC5xxx Series STMicroelectronics SPC5 Series Renesas RH850 Series Infineon AURIX TC3xx Series Microchip PIC32 Series Why AUTOSAR likes SAR ADC over others? SAR ADC working is most suitable due to three major factors mentioned below: High Conversion Speed with Accuracy: SAR ADCs are fast to handle conversion like real-time sensor data conversion while holding its precision as it is. This conversion can be like throttle control, battery management, and other critical functions. Power Efficiency: Power consumption is one of the most important factors in any automotive application especially electric vehicles. SAR ADC consumes comparatively less power rather than ADC like FLASH ADC.  Scalability: SAR ADCs offer a trade-off between speed, resolution, and area, which is crucial in automotive designs where space and performance both matter. Comparing SAR ADC with Flash and Sigma-Delta ADC Flash ADC: The fastest type of ADC, converting signals in just one clock cycle. This speed comes at the cost of power consumption and size, as it requires one comparator per bit of resolution. Given the complex needs of automotive systems, this increased power draw and large footprint make Flash ADCs impractical for most real-time automotive control systems. Sigma-Delta ADC: Offers exceptional accuracy by oversampling the input signal and using noise-shaping techniques. However, its conversion speed is much slower compared to SAR ADCs. This makes it unsuitable for fast, real-time sensor data processing, though it shines in applications where high precision is needed, such as audio or pressure measurement. SAR ADC stands between these two, offering sufficient speed, accuracy, and power efficiency. This balance makes it the top choice for most automotive microcontroller designs, especially in safety-critical applications like engine control, where both speed and accuracy matter. How SAR ADC Works Sample & Hold (S/H) Block: This block holds the analog input signal steady while the ADC performs the conversion. The process begins by capturing the input voltage and freezing it momentarily to allow precise comparisons during the conversion. Comparator: The comparator checks the DAC’s output against the input signal at every stage of the conversion. It decides whether the next bit in the SAR register should be a ‘1’ or a ‘0’ based on whether the input signal is greater or lesser than the DAC output. SAR Register: This is a shift register that stores the output bit by bit as the conversion proceeds. The SAR register’s value evolves with each step of the approximation process, eventually containing the final digital equivalent of the input analog signal. DAC (Digital-to-Analog Converter): The DAC generates a voltage based on the digital bits already stored in the SAR register. The comparator then compares this DAC output with the input signal. The DAC’s resolution is crucial since it must match the resolution of the SAR ADC. Step-by-Step Example: How SAR ADC Calculates an Input Signal Example Setup: Reference Voltage (Vref): 5V Resolution: 4 bits (for simplicity) Input Voltage (Vin): 2.6V Author: Rohan Singhal

Read More »
Kunal Gupta
Author: Kunal Gupta

Author

Kunal Gupta

Leave a comment

Stay Updated With Us

Error: Contact form not found.

      Blog