### Initialize HAL, System, and Get Device Info (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the HAL library, configures the system clock, and retrieves device-specific information like HAL version, unique ID, revision ID, and device ID. It also demonstrates basic tick management and delay functions. ```c #include "stm32h7xx_hal.h" int main(void) { HAL_StatusTypeDef status; /* Initialize the HAL Library - configures Flash prefetch, SysTick, NVIC */ status = HAL_Init(); if (status != HAL_OK) { /* Initialization failed */ while (1); } /* Configure the system clock (application-specific) */ SystemClock_Config(); /* Get HAL version: returns 0x01xx05xx for version 1.xx.5 */ uint32_t hal_version = HAL_GetHalVersion(); /* Get unique device ID (96-bit UID) */ uint32_t uid_w0 = HAL_GetUIDw0(); uint32_t uid_w1 = HAL_GetUIDw1(); uint32_t uid_w2 = HAL_GetUIDw2(); /* Get device revision and device ID */ uint32_t rev_id = HAL_GetREVID(); /* e.g., REV_ID_Y, REV_ID_V */ uint32_t dev_id = HAL_GetDEVID(); /* Device identifier */ /* Main application loop */ while (1) { /* Use HAL_Delay for millisecond delays (blocking) */ HAL_Delay(1000); /* Get current tick value (incremented in SysTick_Handler) */ uint32_t tick = HAL_GetTick(); } } /* SysTick interrupt handler - must call HAL_IncTick() */ void SysTick_Handler(void) { HAL_IncTick(); } ``` -------------------------------- ### Configure and Use Backup SRAM on STM32H7 (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates the configuration and usage of Backup SRAM on an STM32H7 microcontroller. This feature allows data to persist across resets and Standby mode entries, provided a VBAT supply is maintained. The example enables the backup SRAM clock, domain access, and regulator, then writes data to a specific address. ```c #include "stm32h7xx_hal.h" void Backup_SRAM_Example(void) { /* Enable backup SRAM clock */ __HAL_RCC_BKPRAM_CLK_ENABLE(); /* Enable backup domain access */ HAL_PWR_EnableBkUpAccess(); /* Enable backup SRAM regulator */ HAL_PWREx_EnableBkUpReg(); while (!__HAL_PWR_GET_FLAG(PWR_FLAG_BRR)) {} /* Backup SRAM is now available at 0x38800000 (4KB) */ /* Data persists through reset and Standby mode (with VBAT) */ uint32_t *backup_data = (uint32_t *)0x38800000; backup_data[0] = 0xDEADBEEF; } ``` -------------------------------- ### Perform UART Communication (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates UART communication using polling, interrupt, and DMA modes. It includes examples for transmitting data using HAL_UART_Transmit and HAL_UART_Transmit_IT, and receiving data using HAL_UART_Receive and HAL_UART_Receive_IT. Error handling for HAL status is also shown. ```c void UART_Communication_Example(void) { uint8_t tx_data[] = "Hello STM32H7!\r\n"; uint8_t rx_data[32]; HAL_StatusTypeDef status; /* Polling mode transmit (blocking, with 1000ms timeout) */ status = HAL_UART_Transmit(&huart3, tx_data, sizeof(tx_data) - 1, 1000); if (status != HAL_OK) { /* Handle error: HAL_ERROR, HAL_BUSY, HAL_TIMEOUT */ } /* Polling mode receive (blocking) */ status = HAL_UART_Receive(&huart3, rx_data, 10, 5000); /* Interrupt mode transmit (non-blocking) */ status = HAL_UART_Transmit_IT(&huart3, tx_data, sizeof(tx_data) - 1); /* Interrupt mode receive (non-blocking) */ status = HAL_UART_Receive_IT(&huart3, rx_data, 10); } ``` -------------------------------- ### Handle I2C Transfer Complete Callbacks (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Provides example implementations for I2C transfer complete callback functions. These callbacks are invoked by the HAL driver upon successful completion of interrupt-driven I2C master transmit (HAL_I2C_MasterTxCpltCallback) and memory read (HAL_I2C_MemRxCpltCallback) operations. They allow for post-transfer processing. ```c void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) { if (hi2c->Instance == I2C1) { /* Transmit complete */ } } void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) { if (hi2c->Instance == I2C1) { /* Memory read complete */ } } ``` -------------------------------- ### Enter Standby Mode on STM32H7 (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Provides an example of entering Standby Mode on an STM32H7 microcontroller. This is the lowest power mode, where most of the chip is powered down, and RAM content is lost. The code shows clearing flags, enabling a wake-up pin, and initiating the Standby Mode entry. ```c #include "stm32h7xx_hal.h" void Enter_Standby_Mode(void) { /* Clear wake-up flags */ __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); /* Enable wake-up pin (e.g., WKUP1 = PA0) */ HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1_HIGH); /* Enter Standby Mode (lowest power, RAM content lost) */ HAL_PWR_EnterSTANDBYMode(); /* Code never reaches here - system resets on wake-up */ } ``` -------------------------------- ### Get and Control Peripheral Clocks using RCC HAL Driver (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates how to retrieve current system clock frequencies (System Clock, AHB, APB1, APB2) and how to enable or disable clocks for various peripherals. This is essential for initializing and managing power consumption of peripherals. ```c void Clock_Info_Example(void) { /* Get system clock frequencies */ uint32_t sysclk = HAL_RCC_GetSysClockFreq(); /* System clock */ uint32_t hclk = HAL_RCC_GetHCLKFreq(); /* AHB clock */ uint32_t pclk1 = HAL_RCC_GetPCLK1Freq(); /* APB1 clock */ uint32_t pclk2 = HAL_RCC_GetPCLK2Freq(); /* APB2 clock */ /* Enable peripheral clocks */ __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_USART3_CLK_ENABLE(); __HAL_RCC_SPI1_CLK_ENABLE(); __HAL_RCC_TIM2_CLK_ENABLE(); __HAL_RCC_DMA2_CLK_ENABLE(); /* Disable peripheral clocks (for power saving) */ __HAL_RCC_GPIOF_CLK_DISABLE(); } ``` -------------------------------- ### Check Flash Read Protection using STM32H7 HAL Driver Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Provides an example of how to check the read protection status of the Flash memory using the STM32H7 HAL driver. It retrieves the current option byte configuration and checks the RDPLevel to determine if read protection is enabled and at what level. ```c void Flash_Read_Protection_Example(void) { FLASH_OBProgramInitTypeDef OBInit; /* Get current option bytes */ HAL_FLASHEx_OBGetConfig(&OBInit); /* Check read protection level */ if (OBInit.RDPLevel == OB_RDP_LEVEL_0) { /* No read protection */ } else if (OBInit.RDPLevel == OB_RDP_LEVEL_1) { /* Level 1 protection */ } } ``` -------------------------------- ### Control and Manage Timer PWM Output (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Controls the PWM output of a Timer peripheral. It demonstrates starting and stopping PWM generation on a specific channel, dynamically changing the duty cycle using `__HAL_TIM_SET_COMPARE`, and initiating PWM generation with interrupt notifications. This function relies on a pre-initialized Timer handle. ```c void TIM_PWM_Control_Example(void) { /* Start PWM output on channel 1 */ HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); /* Change duty cycle dynamically (0-999 for 0-100%) */ __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 250); /* 25% duty */ HAL_Delay(1000); __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 750); /* 75% duty */ HAL_Delay(1000); /* Stop PWM */ HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1); /* PWM with interrupt notification */ HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_1); } void TIM2_IRQHandler(void) { HAL_TIM_IRQHandler(&htim2); } void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) { if (htim->Instance == TIM2) { /* PWM pulse completed */ } } ``` -------------------------------- ### Perform ADC Conversion and Read Value (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Performs an ADC conversion using polling mode, waits for completion, reads the converted value, and converts it to a voltage. It also demonstrates starting an interrupt-driven conversion. This function relies on a pre-initialized ADC handle (`hadc1`) and assumes a reference voltage and resolution are known. ```c void ADC_Conversion_Example(void) { uint32_t adc_value; float voltage; /* Start conversion (polling mode) */ HAL_ADC_Start(&hadc1); /* Wait for conversion completion */ if (HAL_ADC_PollForConversion(&hadc1, 100) == HAL_OK) { /* Read converted value */ adc_value = HAL_ADC_GetValue(&hadc1); /* Convert to voltage (assuming 3.3V reference, 16-bit resolution) */ voltage = (float)adc_value * 3.3f / 65535.0f; } /* Stop ADC */ HAL_ADC_Stop(&hadc1); /* Interrupt mode */ HAL_ADC_Start_IT(&hadc1); } ``` -------------------------------- ### Configure and Control GPIO Pins (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates GPIO pin configuration for input, output, and external interrupts. It includes enabling clocks, setting pin modes, pull-up/pull-down resistors, speed, writing/reading pin states, and handling external interrupt callbacks. ```c #include "stm32h7xx_hal.h" void GPIO_Configuration_Example(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* Enable GPIO clocks */ __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); /* Configure PA5 as output push-pull (e.g., LED) */ GPIO_InitStruct.Pin = GPIO_PIN_5; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* Configure PC13 as input with pull-up (e.g., button) */ GPIO_InitStruct.Pin = GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); /* Configure PB0 as external interrupt, falling edge */ GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* Enable and set EXTI0 interrupt priority */ HAL_NVIC_SetPriority(EXTI0_IRQn, 2, 0); HAL_NVIC_EnableIRQ(EXTI0_IRQn); /* Write pin high */ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET); /* Write pin low */ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET); /* Toggle pin state */ HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); /* Read pin state */ GPIO_PinState state = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13); if (state == GPIO_PIN_RESET) { /* Button pressed (active low) */ } /* Lock pin configuration (cannot be changed until reset) */ HAL_GPIO_LockPin(GPIOA, GPIO_PIN_5); } /* External interrupt handler */ void EXTI0_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0); } /* User callback for external interrupt */ void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { if (GPIO_Pin == GPIO_PIN_0) { /* Handle interrupt event */ HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); } } ``` -------------------------------- ### Initialize UART Peripheral (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the UART peripheral with specified configuration parameters including baud rate, word length, stop bits, parity, mode, and hardware flow control. This function requires the HAL library and clock configuration to be set up beforehand. It configures GPIO pins for UART communication and enables the peripheral clock. ```c #include "stm32h7xx_hal.h" UART_HandleTypeDef huart3; void UART_Init_Example(void) { /* Configure UART3 (e.g., connected to ST-Link VCP) */ huart3.Instance = USART3; huart3.Init.BaudRate = 115200; huart3.Init.WordLength = UART_WORDLENGTH_8B; huart3.Init.StopBits = UART_STOPBITS_1; huart3.Init.Parity = UART_PARITY_NONE; huart3.Init.Mode = UART_MODE_TX_RX; huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart3.Init.OverSampling = UART_OVERSAMPLING_16; huart3.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE; huart3.Init.ClockPrescaler = UART_PRESCALER_DIV1; if (HAL_UART_Init(&huart3) != HAL_OK) { /* Initialization failed */ Error_Handler(); } } /* MSP initialization callback (called by HAL_UART_Init) */ void HAL_UART_MspInit(UART_HandleTypeDef *huart) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if (huart->Instance == USART3) { __HAL_RCC_USART3_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); /* USART3 GPIO Configuration: PD8=TX, PD9=RX */ GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF7_USART3; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); /* Enable USART3 interrupt */ HAL_NVIC_SetPriority(USART3_IRQn, 5, 0); HAL_NVIC_EnableIRQ(USART3_IRQn); } } ``` -------------------------------- ### Initialize and Configure ADC Peripheral (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the ADC peripheral with specified parameters such as clock prescaler, resolution, scan mode, and conversion settings. It also configures a specific ADC channel for analog input and performs calibration. This function requires the `stm32h7xx_hal.h` header and assumes an `Error_Handler` function is defined. ```c #include "stm32h7xx_hal.h" ADC_HandleTypeDef hadc1; void ADC_Init_Example(void) { ADC_ChannelConfTypeDef sConfig = {0}; hadc1.Instance = ADC1; hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV2; hadc1.Init.Resolution = ADC_RESOLUTION_16B; hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE; hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV; hadc1.Init.LowPowerAutoWait = DISABLE; hadc1.Init.ContinuousConvMode = DISABLE; hadc1.Init.NbrOfConversion = 1; hadc1.Init.DiscontinuousConvMode = DISABLE; hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START; hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; hadc1.Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR; hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; hadc1.Init.OversamplingMode = DISABLE; if (HAL_ADC_Init(&hadc1) != HAL_OK) { Error_Handler(); } /* Configure ADC channel */ sConfig.Channel = ADC_CHANNEL_3; /* PA6 for ADC1 */ sConfig.Rank = ADC_REGULAR_RANK_1; sConfig.SamplingTime = ADC_SAMPLETIME_64CYCLES_5; sConfig.SingleDiff = ADC_SINGLE_ENDED; sConfig.OffsetNumber = ADC_OFFSET_NONE; sConfig.Offset = 0; if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) { Error_Handler(); } /* Run ADC calibration (single-ended mode) */ HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED); } ``` -------------------------------- ### Initialize Window Watchdog (WWDG) - STM32H7xx HAL Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the Window Watchdog (WWDG) timer with a specified window constraint. This function configures the WWDG instance, prescaler, counter, and early wake-up interrupt mode. The WWDG requires refreshing within a specific window to avoid a reset. It also enables the WWDG interrupt. ```c #include "stm32h7xx_hal.h" WWDG_HandleTypeDef hwwdg1; void WWDG_Init_Example(void) { /* Window Watchdog with window constraint */ /* PCLK1 = 120MHz, Counter = 127, Window = 80 */ /* Must refresh when counter is between Window (80) and 64 (0x40) */ __HAL_RCC_WWDG1_CLK_ENABLE(); hwwdg1.Instance = WWDG1; hwwdg1.Init.Prescaler = WWDG_PRESCALER_8; hwwdg1.Init.Counter = 127; /* Maximum count value */ hwwdg1.Init.Window = 80; /* Window value */ hwwdg1.Init.EWIMode = WWDG_EWI_ENABLE; /* Early wake-up interrupt */ if (HAL_WWDG_Init(&hwwdg1) != HAL_OK) { Error_Handler(); } /* Enable WWDG interrupt */ HAL_NVIC_SetPriority(WWDG_IRQn, 0, 0); HAL_NVIC_EnableIRQ(WWDG_IRQn); } ``` -------------------------------- ### Initialize SPI Peripheral (STM32H7 HAL) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the SPI peripheral in master mode with specific configuration parameters. This function sets up the SPI instance, mode, data size, clock polarity/phase, NSS signal, baud rate, and other advanced features. It requires the HAL library and GPIO configuration. ```c #include "stm32h7xx_hal.h" SPI_HandleTypeDef hspi1; void SPI_Init_Example(void) { hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_2LINES; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_LOW; hspi1.Init.CLKPhase = SPI_PHASE_1EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.NSSPMode = SPI_NSS_PULSE_DISABLE; hspi1.Init.NSSPolarity = SPI_NSS_POLARITY_LOW; hspi1.Init.FifoThreshold = SPI_FIFO_THRESHOLD_01DATA; hspi1.Init.MasterSSIdleness = SPI_MASTER_SS_IDLENESS_00CYCLE; hspi1.Init.MasterInterDataIdleness = SPI_MASTER_INTERDATA_IDLENESS_00CYCLE; hspi1.Init.MasterReceiverAutoSusp = SPI_MASTER_RX_AUTOSUSP_DISABLE; hspi1.Init.IOSwap = SPI_IO_SWAP_DISABLE; if (HAL_SPI_Init(&hspi1) != HAL_OK) { Error_Handler(); } } void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if (hspi->Instance == SPI1) { __HAL_RCC_SPI1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /* SPI1: PA5=SCK, PA6=MISO, PA7=MOSI */ GPIO_InitStruct.Pin = GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF5_SPI1; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); } } ``` -------------------------------- ### Configure STM32H7 Power Settings and Enter Sleep Mode (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Configures the STM32H7 microcontroller's power supply, voltage scaling, and enables backup domain access. It then demonstrates entering the Sleep Mode, waking up on interrupt, and resuming the system tick. ```c #include "stm32h7xx_hal.h" void Power_Config_Example(void) { /* Enable Power Clock */ __HAL_RCC_PWR_CLK_ENABLE(); /* Configure power supply (LDO or SMPS) */ HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY); /* Configure voltage scaling (VOS0 = highest performance) */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0); while (!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {} /* Enable backup domain access */ HAL_PWR_EnableBkUpAccess(); } void Enter_Sleep_Mode(void) { /* Suspend SysTick before entering sleep */ HAL_SuspendTick(); /* Enter Sleep Mode - wake up on any interrupt */ HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); /* Resume SysTick after wake-up */ HAL_ResumeTick(); } ``` -------------------------------- ### Initialize I2C Peripheral (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the I2C peripheral (I2C1) with specified configurations for master mode, including timing, addressing mode, and clock settings. It also configures the necessary GPIO pins (PB8 for SCL, PB9 for SDA) for I2C operation. This function is essential before performing any I2C communication. ```c #include "stm32h7xx_hal.h" I2C_HandleTypeDef hi2c1; void I2C_Init_Example(void) { hi2c1.Instance = I2C1; hi2c1.Init.Timing = 0x10C0ECFF; /* 100kHz @ 64MHz PCLK1 */ hi2c1.Init.OwnAddress1 = 0; hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; hi2c1.Init.OwnAddress2 = 0; hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; if (HAL_I2C_Init(&hi2c1) != HAL_OK) { Error_Handler(); } } void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if (hi2c->Instance == I2C1) { __HAL_RCC_I2C1_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /* I2C1: PB8=SCL, PB9=SDA */ GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; GPIO_InitStruct.Pull = GPIO_NOPULL; /* External pull-ups required */ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF4_I2C1; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); } } ``` -------------------------------- ### Initialize and Configure Timer for PWM Output (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes a Timer peripheral (TIM2) for PWM generation. It configures the prescaler, counter mode, period, and clock division for the timer. It also configures a PWM channel with a specific mode, pulse value (duty cycle), and polarity. This function requires the STM32 HAL library. ```c #include "stm32h7xx_hal.h" TIM_HandleTypeDef htim2; void TIM_PWM_Init_Example(void) { TIM_OC_InitTypeDef sConfigOC = {0}; htim2.Instance = TIM2; htim2.Init.Prescaler = 239; /* 240MHz / 240 = 1MHz timer clock */ htim2.Init.CounterMode = TIM_COUNTERMODE_UP; htim2.Init.Period = 999; /* 1MHz / 1000 = 1kHz PWM frequency */ htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE; if (HAL_TIM_PWM_Init(&htim2) != HAL_OK) { Error_Handler(); } /* Configure PWM channel */ sConfigOC.OCMode = TIM_OCMODE_PWM1; sConfigOC.Pulse = 500; /* 50% duty cycle (500/1000) */ sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) { Error_Handler(); } } void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if (htim->Instance == TIM2) { __HAL_RCC_TIM2_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /* PA0 = TIM2_CH1 */ GPIO_InitStruct.Pin = GPIO_PIN_0; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF1_TIM2; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); } } ``` -------------------------------- ### Configure ADC GPIO and Clock (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the necessary GPIO pin for ADC analog input and enables the clock for the ADC peripheral. This function is typically called by the HAL ADC initialization process. It configures a specific pin (e.g., PA6 for ADC1_INP3) as analog input with no pull-up or pull-down resistors. ```c void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { GPIO_InitTypeDef GPIO_InitStruct = {0}; if (hadc->Instance == ADC1) { __HAL_RCC_ADC12_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /* PA6 = ADC1_INP3 */ GPIO_InitStruct.Pin = GPIO_PIN_6; GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); } } ``` -------------------------------- ### Perform SPI Communication (STM32H7 HAL) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates SPI data transmission and reception using polling, transmit-only, and receive-only methods. It also shows how to initiate interrupt-based transmission and reception. This requires a pre-initialized SPI handle and GPIO configuration for chip select. ```c void SPI_Communication_Example(void) { uint8_t tx_data[4] = {0x9F, 0x00, 0x00, 0x00}; /* Read JEDEC ID command */ uint8_t rx_data[4]; /* Chip select low (manual NSS control) */ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET); /* Polling mode: transmit and receive simultaneously */ if (HAL_SPI_TransmitReceive(&hspi1, tx_data, rx_data, 4, 100) == HAL_OK) { /* rx_data contains device response */ } /* Chip select high */ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET); /* Transmit only (polling) */ HAL_SPI_Transmit(&hspi1, tx_data, 4, 100); /* Receive only (polling) */ HAL_SPI_Receive(&hspi1, rx_data, 4, 100); /* Interrupt mode */ HAL_SPI_TransmitReceive_IT(&hspi1, tx_data, rx_data, 4); } void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) { if (hspi->Instance == SPI1) { /* Transfer complete */ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET); /* CS high */ } } ``` -------------------------------- ### Perform I2C Communication Operations (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates various I2C communication patterns using the HAL driver, including checking device readiness, master transmit/receive (polling), memory read/write operations for EEPROM-like devices, and initiating interrupt-driven transmissions and reads. This snippet assumes the I2C peripheral has been initialized. ```c void I2C_Communication_Example(void) { uint8_t device_addr = 0x50 << 1; /* 7-bit address shifted left */ uint8_t tx_data[3] = {0x00, 0x00, 0xAB}; /* Address + data */ uint8_t rx_data[16]; /* Check if device is ready */ if (HAL_I2C_IsDeviceReady(&hi2c1, device_addr, 3, 100) == HAL_OK) { /* Device responded */ } /* Master transmit (polling) */ HAL_I2C_Master_Transmit(&hi2c1, device_addr, tx_data, 3, 1000); /* Master receive (polling) */ HAL_I2C_Master_Receive(&hi2c1, device_addr, rx_data, 16, 1000); /* Memory write (EEPROM-style): device_addr, mem_addr, mem_size, data, size */ uint16_t mem_address = 0x0000; uint8_t write_data = 0x55; HAL_I2C_Mem_Write(&hi2c1, device_addr, mem_address, I2C_MEMADD_SIZE_16BIT, &write_data, 1, 1000); /* Memory read */ HAL_I2C_Mem_Read(&hi2c1, device_addr, mem_address, I2C_MEMADD_SIZE_16BIT, rx_data, 16, 1000); /* Interrupt mode */ HAL_I2C_Master_Transmit_IT(&hi2c1, device_addr, tx_data, 3); HAL_I2C_Mem_Read_IT(&hi2c1, device_addr, mem_address, I2C_MEMADD_SIZE_16BIT, rx_data, 16); } ``` -------------------------------- ### Initialize DMA Memory-to-Memory Transfer (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes a DMA controller for memory-to-memory transfers. This function configures the DMA stream, enables clocks, sets transfer parameters like direction, alignment, mode, and priority, and registers callbacks for transfer completion and errors. It also enables the associated DMA interrupt. ```c #include "stm32h7xx_hal.h" DMA_HandleTypeDef hdma_memtomem; void DMA_MemToMem_Init(void) { __HAL_RCC_DMA2_CLK_ENABLE(); hdma_memtomem.Instance = DMA2_Stream0; hdma_memtomem.Init.Request = DMA_REQUEST_MEM2MEM; hdma_memtomem.Init.Direction = DMA_MEMORY_TO_MEMORY; hdma_memtomem.Init.PeriphInc = DMA_PINC_ENABLE; hdma_memtomem.Init.MemInc = DMA_MINC_ENABLE; hdma_memtomem.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD; hdma_memtomem.Init.MemDataAlignment = DMA_MDATAALIGN_WORD; hdma_memtomem.Init.Mode = DMA_NORMAL; hdma_memtomem.Init.Priority = DMA_PRIORITY_HIGH; hdma_memtomem.Init.FIFOMode = DMA_FIFOMODE_ENABLE; hdma_memtomem.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; hdma_memtomem.Init.MemBurst = DMA_MBURST_INC4; hdma_memtomem.Init.PeriphBurst = DMA_PBURST_INC4; if (HAL_DMA_Init(&hdma_memtomem) != HAL_OK) { Error_Handler(); } /* Register callbacks */ HAL_DMA_RegisterCallback(&hdma_memtomem, HAL_DMA_XFER_CPLT_CB_ID, DMA_TransferComplete); HAL_DMA_RegisterCallback(&hdma_memtomem, HAL_DMA_XFER_ERROR_CB_ID, DMA_TransferError); /* Enable DMA interrupt */ HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 0, 0); HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn); } /* Source and destination buffers (must be in DMA-accessible memory) */ __attribute__((section(".RAM_D1"))) uint32_t src_buffer[256]; __attribute__((section(".RAM_D1"))) uint32_t dst_buffer[256]; void DMA_Transfer_Example(void) { /* Initialize source data */ for (int i = 0; i < 256; i++) { src_buffer[i] = i; } /* Start DMA transfer (polling) */ HAL_DMA_Start(&hdma_memtomem, (uint32_t)src_buffer, (uint32_t)dst_buffer, 256); HAL_DMA_PollForTransfer(&hdma_memtomem, HAL_DMA_FULL_TRANSFER, 1000); /* Start DMA transfer (interrupt mode) */ HAL_DMA_Start_IT(&hdma_memtomem, (uint32_t)src_buffer, (uint32_t)dst_buffer, 256); } void DMA2_Stream0_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_memtomem); } void DMA_TransferComplete(DMA_HandleTypeDef *hdma) { /* Transfer completed successfully */ } void DMA_TransferError(DMA_HandleTypeDef *hdma) { /* Handle DMA error */ } ``` -------------------------------- ### Link DMA to UART for Transmission (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates how to link a DMA controller to a UART peripheral for transmitting data. This function associates the DMA handle with the UART handle and then initiates a DMA-based UART transmission. It requires pre-initialized UART and DMA handles. ```c /* Link DMA to peripheral (e.g., UART TX) */ void DMA_UART_Link_Example(UART_HandleTypeDef *huart, DMA_HandleTypeDef *hdma) { /* Link DMA handle to UART handle */ __HAL_LINKDMA(huart, hdmatx, *hdma); /* Use UART DMA transmit */ uint8_t data[] = "DMA Transfer"; HAL_UART_Transmit_DMA(huart, data, sizeof(data) - 1); } ``` -------------------------------- ### Configure System Clock to 480MHz using RCC HAL Driver (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Configures the system clock to 480MHz by setting up the HSE oscillator and PLL. It also configures voltage scaling for high performance and sets up various peripheral clock dividers. This function requires the HAL library to be initialized. ```c #include "stm32h7xx_hal.h" void SystemClock_Config_480MHz(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /* Configure power supply */ HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY); /* Configure voltage scaling for high performance */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0); while (!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {} /* Configure HSE and PLL */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 5; /* 25MHz / 5 = 5MHz */ RCC_OscInitStruct.PLL.PLLN = 192; /* 5MHz * 192 = 960MHz */ RCC_OscInitStruct.PLL.PLLP = 2; /* 960MHz / 2 = 480MHz SYSCLK */ RCC_OscInitStruct.PLL.PLLQ = 4; /* 960MHz / 4 = 240MHz */ RCC_OscInitStruct.PLL.PLLR = 2; RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_2; RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE; RCC_OscInitStruct.PLL.PLLFRACN = 0; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /* Configure system clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2 | RCC_CLOCKTYPE_D3PCLK1 | RCC_CLOCKTYPE_D1PCLK1; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2; /* 240MHz */ RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2; /* 120MHz */ RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2; /* 120MHz */ RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2; /* 120MHz */ RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2; /* 120MHz */ /* FLASH_LATENCY_4 for 480MHz @ VOS0 */ if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { Error_Handler(); } } ``` -------------------------------- ### Write to Flash Memory using STM32H7 HAL Driver Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates how to write data to the internal Flash memory using the STM32H7 HAL driver. This involves unlocking the Flash, erasing the target sector, programming the data (which must be 256-bit aligned), and finally locking the Flash. Error handling for erase and programming operations is included, along with a basic verification step. ```c #include "stm32h7xx_hal.h" void Flash_Write_Example(void) { FLASH_EraseInitTypeDef EraseInitStruct; uint32_t SectorError = 0; uint32_t Address = 0x08100000; /* Bank 2, Sector 0 start address */ uint64_t Data = 0x0123456789ABCDEF; /* Unlock Flash */ HAL_FLASH_Unlock(); /* Clear all Flash flags */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK2); /* Erase sector before writing */ EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3; EraseInitStruct.Banks = FLASH_BANK_2; EraseInitStruct.Sector = FLASH_SECTOR_0; EraseInitStruct.NbSectors = 1; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { /* Erase failed */ uint32_t error = HAL_FLASH_GetError(); HAL_FLASH_Lock(); return; } /* Program Flash (256-bit / 32-byte aligned for STM32H7) */ /* Data must be 256-bit (32 bytes) aligned */ uint32_t flash_word[8] = {0x11111111, 0x22222222, 0x33333333, 0x44444444, 0x55555555, 0x66666666, 0x77777777, 0x88888888}; if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, Address, (uint32_t)flash_word) != HAL_OK) { /* Programming failed */ uint32_t error = HAL_FLASH_GetError(); } /* Lock Flash */ HAL_FLASH_Lock(); /* Verify written data */ uint32_t *read_ptr = (uint32_t *)Address; for (int i = 0; i < 8; i++) { if (read_ptr[i] != flash_word[i]) { /* Verification failed */ } } } ``` -------------------------------- ### Enter Stop Mode on STM32H7 (C) Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Demonstrates entering the Stop Mode on an STM32H7 microcontroller. This mode offers significant power savings by shutting down most peripherals. The code includes suspending the system tick, entering Stop Mode, and reconfiguring clocks upon wake-up. ```c #include "stm32h7xx_hal.h" void Enter_Stop_Mode(void) { /* Configure wake-up sources (e.g., EXTI) before entering Stop */ HAL_SuspendTick(); /* Enter Stop Mode (D1 domain) */ HAL_PWREx_EnterSTOPMode(PWR_MAINREGULATOR_ON, PWR_STOPENTRY_WFI, PWR_D1_DOMAIN); /* After wake-up: reconfigure clocks (PLL is stopped in Stop mode) */ SystemClock_Config_480MHz(); HAL_ResumeTick(); } ``` -------------------------------- ### Initialize Independent Watchdog (IWDG) - STM32H7xx HAL Source: https://context7.com/stmicroelectronics/stm32h7xx-hal-driver/llms.txt Initializes the Independent Watchdog (IWDG) with a specified timeout period. This function configures the IWDG instance, prescaler, and reload value. The IWDG operates independently using the LSI oscillator and requires periodic refreshing to prevent a system reset. Ensure HAL_IWDG_Init returns HAL_OK. ```c #include "stm32h7xx_hal.h" IWDG_HandleTypeDef hiwdg1; void IWDG_Init_Example(void) { /* Independent Watchdog with ~1 second timeout */ /* LSI = 32kHz, Prescaler = 64, Reload = 500 */ /* Timeout = (Reload * Prescaler) / LSI = (500 * 64) / 32000 = 1s */ hiwdg1.Instance = IWDG1; hiwdg1.Init.Prescaler = IWDG_PRESCALER_64; hiwdg1.Init.Reload = 500; hiwdg1.Init.Window = IWDG_WINDOW_DISABLE; if (HAL_IWDG_Init(&hiwdg1) != HAL_OK) { Error_Handler(); } /* IWDG starts running immediately after init */ } ```