Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

411 University St, Seattle, USA

engitech@oceanthemes.net

+1 -800-456-478-23

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

Tigger MUX Control(TRGMUX) Peripheral in S32K144 MCU

What is TRGMUX peripheral? TRGMUC provides an extremely flexible mechanism for connecting various trigger sources to multiple pins/peripherals. The trigger multiplexer (TRGMUX) module allows software to configure the trigger inputs for various peripherals.   The TRGMUX module allows software to select the trigger source for peripherals.   TRGMUX is a peripheral which provides mechanisms for connecting various trigger sources to multiple pins/peripherals. Each peripheral that accepts external triggers usually has one specific 32-bit trigger control register. Each control register supports upto 4 triggers and each trigger can be selected from available trigger sources.   Author: Kunal Gupta

Read More »

PDB (Programmable Delay Block) Peripheral in automotive microcontroller (NXP S32K144)

What is Programmable Delay Block(PDB) peripheral? PDB provides controllable delays from either an internal or an external trigger, or a programmable interval tick, to the hardware trigger inputs of ADCs. PDB can also provide pulse outputs that are used as the sample window in the CMP block.   The PDB contains a counter whose output is compared to several different digital values. If the PDB is enabled, then a trigger input event will reset the PDB counter and make it start to count. A trigger input event is defined as a rising edge being detected on a selected trigger input source, or if a software trigger is selected and the Software Trigger bit (SC[SWTRIG]) is written with 1 Author: Kunal Gupta

Read More »
CAN Bit TIming
Automotive Protocols
Rohan Singhal

CAN Bit Timing Explained

Bit timing in CAN is all about ensuring that every node on the network can correctly interpret the bits being transmitted. This synchronization is crucial for maintaining the integrity and efficiency of data communication. Bit Segmentation Each bit in a CAN frame is divided into several segments: Synchronization Segment (Sync_Seg): This is the part where the actual synchronization occurs. It’s always one-time quantum (TQ) long and helps align the clocks of all nodes on the network. Propagation Segment (Prop_Seg): This segment compensates for the physical delay in signal propagation across the network. Phase Segment 1 (Phase_Seg1): This is used to compensate for edge phase errors by lengthening the bit time if necessary. Phase Segment 2 (Phase_Seg2): Similar to Phase_Seg1, but it shortens the bit time if necessary. Each of these segments is made up of a certain number of time quanta (TQ), which are the smallest time units in a CAN network. Sample Point The sample point is a critical point within the bit where the bus level is read and interpreted as a logical value. Here’s why it’s so important: Accurate Bit Reading: The sample point is where the CAN controller reads the bit value. It is crucial to set the sample point accurately to minimize errors due to signal noise or other disturbances on the bus. Preferred Value: Typically set at 87.5% of the bit time, this value is preferred by protocols like CANopen and DeviceNet. This means that the bit is sampled after 87.5% of its duration has passed. Adjustable Range: The sample point can vary from 50% to 90% of the bit time, allowing flexibility depending on the network requirements and conditions. For example, ARINC 825 uses a default value of 75%. Noise Minimization: Setting the sample point correctly helps in minimizing the impact of signal noise. Sampling too early or too late can lead to incorrect bit interpretation, especially in noisy environments. Understanding Bit Rate and Bit Timing Bit Rate The bit rate in CAN communication refers to the speed at which data is transmitted over the CAN bus, typically measured in bits per second (bps). The bit rate is a crucial parameter because it determines how quickly data can be sent and received between nodes on the network. Common bit rates in CAN systems include 125 kbps, 250 kbps, and 500 kbps, with some systems operating at even higher speeds, such as 1 Mbps. Bit Timing Bit timing in CAN communication is the precise control of the duration and positioning of each bit transmitted on the bus. Proper bit timing ensures that all nodes on the network sample the bits at the same point, leading to accurate and synchronized data transmission. Bit timing is divided into several segments within each bit time, which collectively ensure robust and reliable communication. How Bit Timing Ensures Synchronization To maintain synchronization, the CAN controller can adjust the length of a bit by an integral number of time quanta (TQ). The maximum value of these adjustments is termed the Synchronization Jump Width (SJW). Hard Synchronization: Occurs on the recessive-to-dominant transition of the start bit. The bit time is restarted from this edge. Resynchronization: Occurs when a bit edge doesn’t occur within the Sync_Seg in a message. One of the Phase Segments is shortened or lengthened, depending on the phase error, up to the SJW. Factors Affecting Bit Rate Four primary factors influence the CAN bit rate: Oscillator Tolerance: Variations in the oscillator frequency can affect the timing accuracy. High-precision oscillators are essential for maintaining a stable bit rate. Propagation Delay: The physical length and quality of the CAN bus can introduce delays. Prop_Seg is adjusted to compensate for these delays. Network Load: Heavy network traffic can lead to delays and timing issues. Proper network design and bit timing configuration help mitigate these problems. Bus Length: Longer bus lengths introduce more propagation delay, requiring adjustments in the Prop_Seg to maintain synchronization. Prescaler Division The prescaler is used to divide the clock frequency to generate the required clock frequency for CAN. For example, if the clock frequency is 48 MHz and we need an 8MHz CAN clock, the prescaler value would be 6. How the Prescaler Division Works Clock Frequency: The original clock frequency provided by the oscillator. Prescaler Value: The value by which the original clock frequency is divided to achieve the desired CAN Clock Frequency. IMPORTANT The CAN system clock is chosen so that the desired CAN bus Nominal Bit Time (NBT) is an integer number of time quanta (CAN system clock periods) from 8 to 25. Time Quanta Definition: The time quantum (tQ) is the basic time unit in CAN bit timing. It is derived from the CAN system clock divided by the prescaler. Calculation: For example, if the CAN system clock is 48 MHz and the prescaler is set to 6, then: Nominal Bit Time (NBT) Definition: The Nominal Bit Time (NBT) is the total duration of a single CAN bit, measured in time quanta (tQ). It is the sum of the time segments within a bit period: Sync_Seg, Prop_Seg, Phase_Seg1, and Phase_Seg2. Components: Sync_Seg: The synchronization segment, always 1 tQ. Prop_Seg: The propagation delay segment, compensates for the signal propagation delay. Phase_Seg1: The first phase segment, can be adjusted to resynchronize the clock. Phase_Seg2: The second phase segment, also adjustable for resynchronization. Calculation: Practical Example of Bit Timing Calculation For calculating Bit Time and Segmentation, some important parameters are taken into account before starting the calculation. Parameters: Bit rate MCU Clock/Oscillator Frequency Bus length Bus propagation delay Propagation delay of TxD plus RxD offered by CAN Transceiver But, usually, values like total propagation delay offered by CAN transceiver, Bus length, and Bus propagation delay, are pre-defined values in their hardware datasheet. Question: Conclusion Understanding CAN bit timing and how the bit rate is adjusted is crucial for ensuring reliable communication in a CAN network. By properly configuring the timing parameters and taking into account factors like oscillator tolerance, propagation delay, network load, and bus length,

Read More »
Kunal Gupta
Author: Kunal Gupta

Author

Kunal Gupta

Leave a comment

Stay Updated With Us

Error: Contact form not found.

      Blog